提问者:小点点

在异步函数内部,从回调函数返回值将返回Promise(未定义)[重复]


我是异步编程的新手,我面临着与这个问题类似的问题,在这个问题中,建议的方法使用回调,但我尝试使用承诺和异步等待函数来实现。我在控制台中未被定义。这是我的例子。我错过了什么?

 //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));

共1个答案

匿名用户

使查询函数返回承诺

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));