What is the best way to obtain a promise from an interface or the content of a promise?

I am seeking clarity on a specific issue that seems to be quite common after researching similar questions. I am currently learning by studying and attempting to replicate another person's code. One of the methods in an injectable returns a promise, and I am trying to access the data within this promise from a different method where it has been injected.

Here is the code snippet I am referring to:

getLists(){ 
    return this.isReady()
    .then(()=>{
      return this.database.executeSql("SELECT * from list", [])
      .then((data)=>{
        let lists = [];
        for(let i=0; i<data.rows.length; i++){
          lists.push(data.rows.item(i));
          console.log(i);
        }
        return lists;
      })
    })}

And here is my attempt at implementing something similar, which is not functioning correctly due to mismatched types (string[] does not match Promise)

`

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DatabaseService } from '../../app/database-service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[DatabaseService],
})
export class HomePage {
  listas:string[];

  constructor(public navCtrl: NavController, private service:DatabaseService ) {


  }
  getLists(){
  this.listas=this.service.getLists();
  }
  getList(){
    this.service.getList(0);
  }
  addList(){
    this.service.addList("Shazam");
  }
  deleteList(){
    this.service.deleteList(0);
  }

}`

Thank you for your understanding and patience as I navigate through this challenge.

Answer №1

To utilize the listas variable, simply assign it when the data becomes available:

 loadData(){
   this.service.fetchData().then(data => this.listas = data);
  }

You can also achieve the same result using a different syntax:

 async loadData(){
   this.listas = await this.service.fetchData();
  }

Answer №2

If you're wondering why a promise is returned instead of a list, it's because the Promise.then function itself returns a promise.

When you return this.isReady().then() in your getLists() function, you are actually returning a promise to the caller.

The code following that simply modifies what is returned within that promise, not the promise itself.

For more information on promises in JavaScript, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

It's worth noting that promises wait for other promises to resolve before moving on to the next then() method. For example, consider the following code snippet (which will only run in Chrome due to lambda syntax):

getPromise().then(a => console.log('a', a));

function getPromise() {
    return new Promise((res, rej) => {
        res(1);
    }).then(b => {
        console.log('b', b);
        return new Promise((res, rej) => {
            setTimeout(() => res(2), 3000);
        })
    }).then(c => {
        console.log('c', c);
        return new Promise((res, rej) => {
            setTimeout(() => res(3), 3000);
        })
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my Page to not update when the Context changes?

In my Base Context, I store essential information like the current logged-in user. I have a User Page that should display this information but fails to re-render when the Context changes. Initially, the Context is empty (isLoaded = false). Once the init fu ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

React: Issue with onClick not triggering on a div element

UPDATE: Good news! After some troubleshooting, it turns out that everything is actually working fine. The issue was just a mistake in my className Ternary causing the class not to apply correctly. However, I'm still curious about why onClick does not ...

A guide on utilizing radio buttons to delete specific rows within a table with the help of AngularJS

My current issue involves using radio buttons to delete rows in a table. The problem I'm encountering is that multiple rows are being deleted at once instead of just one. You can view an image of my table here. As we all know, with radio buttons, onl ...

Encountering the ECONNREFUSED 127.0.0.1:3306 error message while trying to launch my node.js application

After launching my node.js application, I encountered the following error message: SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306 This is what I was trying to do: - create a user: CREATE USER 'main'@'localhost' ...

Encountered a Node error while attempting to connect: failed to establish connection within the time limit when accessing the

Currently, I am following a tutorial guide on how to Authenticate using NodeJs and JSON web tokens. I have already set up my server.js, config.js, and user model. Initially, my application was running smoothly on localhost:3333 (unfortunately, my 8080 po ...

Toggling different <div> sections with button clicks

I have a specific objective that I am working towards. For more information, please visit this page: Located at the bottom right corner is a <div> which contains two buttons on either side. Currently, this <div> houses a single Google chart. ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HT ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Error: Looking for guidance on how to handle undefined or null values in an object. Lead me towards the correct solution

I've come across several solutions online for this issue, but being new to this, I haven't been successful in making it work. It may sound trivial, but I could really use some help :) The error: TypeError: Cannot convert undefined or null to ob ...

Using express to activate http compression

Currently experimenting with the Darksky API and came across a query parameter that caught my attention: The extend=hourly option is available. With this option, hour-by-hour data for the next 168 hours will be returned rather than just the next 48. It i ...

AngularJS - assessing an expression within a validator directive

I am working with a custom validation attribute directive that allows for expressions, such as: <input type="text" uiSelectRequired="isParam == true"/> How can I evaluate this expression within my directive without using an isolated scope? Thank y ...

Ways to extract the ASP.net variable value and place it inside a JavaScript textbox

Currently, I'm in the process of developing Javascript code for an ASP.net page. Within my coding framework, the string "foo" is linked to a string variable called myString. In order to transfer the value of myString to a JavaScript variable, I incl ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

The function RegisterClientScriptInclude seems to be malfunctioning inexplicably

I've been struggling for over 2 days trying various solutions and searching online, but I can't seem to get RegisterClientScriptInclude to function properly like everyone else. For starters, I am using .NET 3.5 Ajax and incorporating javascript ...

Is there a way to convert an array into a single comma-separated value using parameters?

Is there a way to parameterize an array as a single name-value pair that is comma separated? I have tried using jQuery $.param, but it creates a parameter for each value in the array instead of just one. Unfortunately, it seems that there is no option or s ...

Transitioning NodeJS from local development to a live website

After successfully creating a site using NodeJS with one-page HTML/jQuery, everything is functioning properly on localhost. However, I am facing issues when trying to put the site online at www.xxxx.com. I already have a registered .com domain, but I am un ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

A guide on extracting data from the constructor within a collection of objects

I am currently working on a React component called maintoolbar.tsx. This component receives a grid object as a prop. import React from 'react'; import { Grid } from '../grid'; interface PropsInterface { grid: Grid; } const MainTool ...

Stopping an Angular UI accordion from opening programmatically with a click action

My goal is to implement pre-validation before an accordion expands without the need for an extra button in the header. For example, when someone clicks on the accordion header and it should not close under certain conditions, I want to include some conditi ...