I have thoroughly read through google and these 2 previous questions on stack overflow but as a noob Im still not getting the result i expect
How do I return the response from an asynchronous call?
How do I convert an existing callback API to promises?
In particular, one answer above says
"ES2017+: Promises with async/await
The ECMAScript version released in 2017 introduced syntax-level support for asynchronous functions. With the help of async and await, you can write asynchronous in a "synchronous style". The code is still asynchronous, but it's easier to read/understand."
...so that is the direction I have gone, using async/await
I have a button on a react native page that runs this code
onPressRefreshButton = async () => {
const rows = await ReturnAllRowsFromTable('NameOfTable')
console.log(rows)
}
This function is in an imported file external to the above, it returns a list of all the rows in the table
export async function ReturnAllRowsFromTable(tableName){
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM ' + tableName + ';',
[],
(tx, results) => {
if (results && results.rows && results.rows._array) {
console.log('all rows returned')
console.log(results.rows.item(0))
return await results.rows._array
}
},
(tx, error) => {
console.log(error);
}
)
});
}
When I press the button I get the following in the console
undefined
all rows returned
Object {
"key": "value",
"key2": "value",
}
So it appears as if the console.log(rows)
line is executing before the const rows = await ReturnAllRowsFromTable('NameOfTable')
line even though I have async/await calls all through each function.
What have I done wrong?