Mar*_*kee 6 javascript callback node.js promise async-await
我是异步编程的新手,我面临着类似于这个问题的问题,在这个问题中建议的方法使用回调,但我正在尝试使用 Promises 和 async-await 函数来做到这一点。我在控制台中未定义。这是我的例子。我错过了什么?
//Defining the function
async query( sql, args ) {
const rows = this.connection.query( sql, args, async( err, rows ) =>
{
if ( err )
throw new Error(err);
return rows;
} );
}
//calling the function here
db.query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));
Run Code Online (Sandbox Code Playgroud)
让你的query函数返回一个Promise
function query(sql, args) {
return new Promise(function (resolve , reject) {
this.connection.query(sql, args, (err, rows) => {
if (err)
reject(err);
else
resolve(rows)
});
});
}
//calling the function here
query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5183 次 |
| 最近记录: |