我已经彻底阅读了谷歌和前两个关于堆栈溢出的问题,但作为一个菜鸟我仍然没有得到我期望的结果
How do I return the response from an asynchronous call?
How do I convert an existing callback API to promises?
特别是,上面的一个答案说
“ES2017 +:与异步/等待的承诺
2017年发布的ECMAScript版本引入了异步函数的语法级支持。在async和await的帮助下,您可以在“同步样式”中编写异步。代码仍然是异步的,但它更容易阅读/理解。“
...这就是我走的方向,使用async / await
我在运行此代码的react本机页面上有一个按钮
onPressRefreshButton = async () => {
const rows = await ReturnAllRowsFromTable('NameOfTable')
console.log(rows)
}
此函数位于上面外部的导入文件中,它返回表中所有行的列表
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);
}
)
});
}
当我按下按钮时,我在控制台中得到以下内容
undefined
all rows returned
Object {
"key": "value",
"key2": "value",
}
所以看起来好像console.log(rows)
线在const rows = await ReturnAllRowsFromTable('NameOfTable')
线之前执行,即使我有async / await全部通过每个函数调用。
我做错了什么?
您没有返回事务的结果,基于提供的API,您将创建一个新的Promise
来包装事务操作并返回它,以便您可以await
其结果:
export async function ReturnAllRowsFromTable(tableName){
return new Promise(function(resolve, reject) {
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))
resolve(results.rows._array); // return result to caller
}
},
(tx, error) => {
console.log(error);
reject(error); // return error to caller
}
)
});
});
}