Reputation: 341
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
i need to get like this example
var customer = getCustomer();
customer.name;
customer.email;
Upvotes: 8
Views: 16214
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
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
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
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