Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value of promise using angular 2

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;
like image 496
PAncho Avatar asked Aug 24 '16 13:08

PAncho


1 Answers

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);
    });
like image 133
sebaferreras Avatar answered Sep 29 '22 20:09

sebaferreras