【问题标题】:Array.push() inside Model.findOne() in Node jsNode js 中的 Model.findOne() 中的 Array.push()
【发布时间】:2020-07-20 17:14:54
【问题描述】:

我声明ids 数组并将id 推入其中。

我使用 Node.js 和猫鼬

这是我的代码

let ids = []
for (let i = 0; i < chatLen; i++) {
    let id = chats[i].sender_id == reqUserid ? chats[i].receiver_id : chats[i].sender_i
    if (ids.indexOf(id) == -1) {
        User.findOne({
            _id: new ObjectId(id)
        }).then(data => {
            if (data && data._id) {
                console.log(data);
                ids.push(data._id)
                socket.emit('GetChatter', data)
            }
        })
    }
}

如何将 id 推送到 ids 数组中?

【问题讨论】:

  • 问题是什么?
  • 如何将 id 推送到 ids 数组中
  • 这应该按照您的方式工作。请注意 User.findOne() 是 async 并且 for 循环将在加载用户之前运行到下一次迭代。但最终ID还是应该被推送...
  • 但这也意味着if (ids.indexOf(id) == -1) {由于异步执行而无法按预期工作
  • 我在代码中所做的更改以实现if (ids.indexOf(id) == -1) {。

标签: javascript node.js mongodb mongoose socket.io


【解决方案1】:

您的代码正在运行,因为 User.findOne() 是 async 函数。

试试这个代码。

let chatLen = chats.length;
GetUserFromChat(chatLen)
async function GetUserFromChat(chatLen) {
    let ids = []
    for (let i = 0; i < chatLen; i++) {
        let id = chats[i].sender_id == reqUserid ? chats[i].receiver_id : chats[i].sender_id;
        console.log(ids);

        if (ids.indexOf(id) == -1) {
            await User.findOne({
                _id: new ObjectId(id)
            }).then(data => {
                if (data && data._id) {
                    socket.emit('GetChatter', data)
                    ids.push(data._id)
                }
            })
        }
    }
}

或

如果你想要性能,请使用它。

(async () => {
let FriendLen = req.user.friends.length;
const promises = [];
for (let i = 0; i < FriendLen; i++) {
    const acc = Events.findOne({ host_id : req.user.friends[i] });
    promises.push(acc)
}
const events = await Promise.all(promises);
})();

【讨论】:

    【解决方案2】:

    您的代码已评估async,这就是您的脚本无法按预期工作的原因。如果你想执行迭代synchronously,你可以使用async / await:

    function waitForUserIdAndEmitData(id) {
        return User.findOne({
            _id: new ObjectId(id)
        }).then(data => {
            if (data && data._id) {
                socket.emit('GetChatter', data)
                return data._id
            }
        })
    }
    
    async function iterate(chatLen) {   // <- note "async"
    
      let ids = []
    
       for (let i = 0; i < chatLen; i++) {
         let id = chats[i].sender_id == reqUserid ? chats[i].receiver_id : chats[i].sender_i
         if (ids.indexOf(id) == -1) {
           const userId = await waitForUserId(id) // <- note "await"
           ids.push(userId)
         }
       }
       console.log(ids)
    }
    
    iterate(chatLen)
    

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 2016-08-03
      • 2014-04-14
      • 2022-01-20
      • 2012-12-24
      • 2018-10-12
      • 2017-12-31
      • 2021-05-25
      • 1970-01-01
      相关资源
      最近更新 更多