【问题标题】:Update old function to async await将旧函数更新为异步等待
【发布时间】:2019-08-31 10:18:35
【问题描述】:

我想将此函数更新为异步,但无法获取从交互对象映射的用户对象以返回相同格式的数据,并且我在异步函数中的值在客户端出现为零。在控制台中,我只得到 Promise 对象并且未定义。

这是我的工作代码:

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

如果我只返回用户对象,则错误会更具体,并表示“firstName”为 nil。返回用户映射的对象给了我一个关键错误。

【问题讨论】:

  • interactions.map() 仍然返回一个数组,因此您仍然需要 Promise.all() 来获得可以等待的承诺。
  • 如此简单!我爱你!! @MarkMeyer 非常感谢!
  • await 仅当它后面的表达式返回一个 promise 时才起作用。对map 的调用会返回一个数组,因此不会像您希望的那样运行。你不能真正用一个 await 替换 Promise.all。你的代码应该更像await Promise.all(fn.map( ... ))

标签: javascript node.js async-await sequelize.js


【解决方案1】:

试试这个:

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

【讨论】:

  • 非常感谢您花时间回答。祝你好运。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多