在异步函数中,从回调函数返回值返回 Promise(undefined)

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)

Ali*_*Ali 6

让你的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)

  • 这行得通,但我们不能在查询函数中使用 async 和 await 吗? (2认同)