Reputation: 387
I am developing a mobile application with React Native. I query a database and I retrieve the data with a "SELECT" request.
The problem is that I can't get the result of this request. I would like to retrieve the result of this request is stored all the elements in a list variable
Here is the code of the "Select" request:
listProduct()
{
return new Promise((resolve) =>
{
const db = SQLite.openDatabase('database.db')
db.transaction(
tx => {
tx.executeSql('select * from FRIDGE_PRODUCT', [], (trans, result) => {
let row = result.rows;
resolve(row)
return row
});
}
);
});
}
And there is the call of this function from another script:
async function loadproduct() {
let result = await db.listProduct();
return result
}
let row = loadproduct()
The problem is that if I want to display the row variable in the console I get this:
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
Whereas if I print the result directly in the function like this:
async function loadproduct() {
let result = await db.listProduct();
console.log(result)
return result
}
I get the right result:
Object {
"DATE": "10/10/2020",
"IDPRODUCT": 1,
"IMAGEURL": "imageurl",
"PRODUCTNAME": "orange",
}
How can I store the result in a varialbe ?
I try that: How to access the value of a promise? but it doesn't help me too much.
Upvotes: 2
Views: 1682
Reputation: 172
The loadproduct
function is an asynchronous function which returns a Promise object. This means it won't be completed immediately, and you'll have to wait for it to finish. When the promise is resolved/finished it will return your results.
Right now you are setting the row
variable to the Promise object itself, which is why you see Promise {something}
in the console.
Before getting the results, JavaScript must wait for the SQL query to finish. When it is completed it will run the then
or catch
method, depending on if it was successful or not.
You can wait for it to finish using the then()
function:
loadproduct().then(row => doSomethingWithRow(row))
Or if you are already inside an async function you can use the await
keyword
let row = await loadproduct()
Upvotes: 2