How to return value of promise using angular 2

13,967

Solution 1

first, you need func to get all your data:

getAll(): Promise<Phrase[]> {
    return phrasesPromise;
}

second, if you need one item you can use

ngOnInit() {
    this.phraseService
        .getAll()
        .then((result: Phrase[]) => this.phrases = result);
}

Solution 2

Promises provide us with abstractions that help us deal with the asynchronous nature of our applications. Since we don't know how much time will those operations take (and therefore, when is the data going to be available) you need to use the then() method to execute some code when the data is ready to be used:

this.getCustomer()
    .then((data) => {
        // Here you can use the data because it's ready
        // this.myVariable = data;
    })
    .catch((ex) => {
        console.log(ex);
    });

Solution 3

This is a Promise, so you need to use then:

getCustomer()
    .then(customer => {
        customer.name;
        customer.email;
    });

If you are using TypeScript, or a version of JavaScript that supports async/await, you can do this:

var customer = await getCustomer();
customer.name;
customer.email;

The above will need to be in an async function, like so:

async displayCustomerDetails() {
    var customer = await getCustomer();
    customer.name;
    customer.email;
}

Solution 4

You can use the await operator like this:

getCustomer(): Promise<any> {
    [...]
}

async functionThatNeedsCustomer() {
    const customer = await getCustomer();
    const name = customer.email;
    const email = customer.email;
}

The await operator awaits form the Promise to return the result. This can only be done inside an async function (making a function async will make it to return a promise itself).

Share:
13,967
PAncho
Author by

PAncho

Updated on June 05, 2022

Comments

  • PAncho
    PAncho almost 2 years

    This is my promise function i need to return the value of rs.rows.item(0);

         public getCustomer()  : any
      {
            let  db =  window.sqlitePlugin.openDatabase({name: 'data.db', location: 'default'});
            return new Promise((resolve, reject) =>
            {
                db.transaction(function(tx)
                {
                    tx.executeSql('SELECT * FROM customer ORDER BY customerId DESC LIMIT 1', [], function(tx, rs)
                    {
                         return resolve(rs.rows.item(0));
                    }, 
                    function(tx, error) 
                    {
                        console.log('SELECT error: ' + error.message);
                        reject(error);
                    });
                });
            });    
      }
    

    the return value i got an object like this image image result

    i need to get like this example

    var customer = getCustomer();
    customer.name;
    customer.email;