使用异步和等待处理承诺

时间:2019-07-22 10:00:47

标签: node.js sequelize.js

我想使用异步并等待处理承诺。我想在下面的示例中使用它:

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()。 (拒绝ID:3)

1 个答案:

答案 0 :(得分:2)

首先,您应该返回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)
}