Javascript 将旧函数更新为异步等待
我想将此函数更新为async,但无法使从interactions对象映射的users对象以相同的格式返回数据,并且我在async函数中的值在客户端为零。在控制台中,我只得到Promise对象和未定义的对象 这是我的工作代码:Javascript 将旧函数更新为异步等待,javascript,node.js,async-await,sequelize.js,Javascript,Node.js,Async Await,Sequelize.js,我想将此函数更新为async,但无法使从interactions对象映射的users对象以相同的格式返回数据,并且我在async函数中的值在客户端为零。在控制台中,我只得到Promise对象和未定义的对象 这是我的工作代码: Interaction.findAll({ where: { targetUserId: fbId, status: 'invited' }, order: [['createdAt', 'DESC']] }).th
Interaction.findAll({
where: {
targetUserId: fbId,
status: 'invited'
},
order: [['createdAt', 'DESC']]
}).then(function (interactions) {
Promise.all(interactions.map(interaction =>
User.findOne({
where: {
facebookUserId: interaction.userId
},
attributes: ['firstName', 'facebookUserId', 'pictureUrl']
}))).then(function (users) {
res.status(200).send(users.map(user => user.dataValues));
})
},
这是我目前所拥有的,但我的数据没有以相同的格式返回到客户端:
try {
const interactions = await Interaction.findAll({
where: {
targetUserId: userId,
status: 'invited'
},
attributes: ['lastReplyAt', 'seen', 'userId'],
})
const users = await interactions.map(interaction => User.findOne({
where: {
facebookUserId: interaction.userId
},
attributes: ['firstName', 'facebookUserId', 'pictureUrl'],
}))
res.status(200).send(users.map(user => user.dataValues));
}
catch (error) {
console.log(error);
res.status(500).send(error);
}
如果我只返回users对象,则错误更为具体,并表示“firstName”为nil。返回用户映射的对象时出现一个关键错误。请尝试以下操作:
interaction = await Interaction.findAll({
where: {
targetUserId: fbId,
status: 'invited'
},
order: [['createdAt', 'DESC']]
})
users = await Promise.all(interactions.map(interaction => {
User.findOne({
where: {
facebookUserId: interaction.userId
},
attributes: ['firstName', 'facebookUserId', 'pictureUrl']})
})
res.status(200).send(users.map(user => user.dataValues));
interactions.map()
仍然返回一个数组,因此您仍然需要Promise.all()
来获得您可以等待的承诺。非常简单!我爱你@MarkMeyer非常感谢你!仅当表达式返回一个承诺时才等待函数。调用map
返回一个数组,因此它的功能与您希望的不一样。你真的不能用一个承诺来代替承诺。您的代码应该更像等待承诺。所有(fn.map(…)
非常感谢您花时间回答。祝你万事如意。