【发布时间】:2018-07-09 12:13:55
【问题描述】:
我是异步编程的新手, 我面临与question 类似的问题,在这个问题中建议的方法使用回调,但我正在尝试使用 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));
【问题讨论】:
-
你缺少的是
await。 -
您不要将
async放在回调函数上。您使用 Promise 构造函数,然后在调用函数时使用await而不是then。
标签: javascript node.js callback promise async-await