【问题标题】:Use of async and await to handle promise使用 async 和 await 处理 promise
【发布时间】:2019-07-22 10:00:47
【问题描述】:

我想使用 async 和 await 来处理承诺。我想在下面给出的示例中使用它:

exports.getUserData = async function(userId){
        let query = {};
        if(userId){
            query.where = {userid : req.query.id}
        }
        let data;
        try{
            data = await entity.DB_User.findAll(query);
        }catch(error){
            console.log(error);
        }
    }

在执行时它给了我一个错误

错误:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 使用 .catch()。 (拒绝编号:3)

【问题讨论】:

  • 哪一行报错?
  • 请提供更多代码细节
  • 未捕获的异常是什么?
  • 将所有代码保存在 try 块中的方法中。
  • 您将 userId 传递给函数,而不是将其传递给查询 if(userId){ query.where = {userid : req.query.id} // userId 而不是 req .query.id ? }

标签: node.js sequelize.js


【解决方案1】:

首先,您应该返回data

我认为调用getUserData 时会引发异常。试试:

getUserData()
    .then(data => console.log)
    .catch(err => console.log) // this line prevent the UnhandledPromiseRejection

// or in async context

try {
    const data = await getUserData()
    console.log(data)
} catch (err) {
    console.log(err)
}

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2017-10-26
    相关资源
    最近更新 更多