PAncho
PAncho

Reputation: 341

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;

Upvotes: 8

Views: 16214

Answers (4)

Volodymyr Khmil
Volodymyr Khmil

Reputation: 1244

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);
}

Upvotes: 3

James Monger
James Monger

Reputation: 10685

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;
}

Upvotes: 3

Manuel Dom&#237;nguez
Manuel Dom&#237;nguez

Reputation: 188

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).

Upvotes: 1

sebaferreras
sebaferreras

Reputation: 44669

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);
    });

Upvotes: 8

Related Questions