【问题标题】:Inside async function, returning value from a callback function returns Promise(undefined) [duplicate]在异步函数内部,从回调函数返回值返回 Promise(undefined) [重复]
【发布时间】: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


【解决方案1】:

让您的 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));

【讨论】:

  • 这行得通,但我们不能在查询函数中使用 async 和 await 吗?
  • 如果你真的想在外部查询函数中使用 async/await,你可以“await new Promise(...)”。无论如何,你仍然需要一个 Promise 来转换回调,无论你是使用 async/await 还是只是简单的 Promises。
猜你喜欢
  • 2019-01-27
  • 2019-12-29
  • 2020-07-09
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
相关资源
最近更新 更多