NodeJS数组同步吗? [英] NodeJS arrays synchronous?

查看:78
本文介绍了NodeJS数组同步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var membersStatArray = [];
membersArray.forEach(function(member) {
    db.doneTodo
        .find({ 'victor._id': member._id })
        .then((arrayOfUserVictories) => {
            membersStatArray.push({
                email: member.email,
                victories: arrayOfUserVictories.length
            });
        })
});
console.log(membersStatArray);

什么是数据库并不重要.

我知道NodeJS是异步的,但是添加到数组然后打印数组的方法又是什么呢?

I know NodeJS is asynchronous but then what is a way of adding to the array and THEN printing the array?

现在发生的是

console.log(membersStatArray) --> [] 

因为它需要空数组.

这是怎么回事?

推荐答案

修改代码,使其使用

Modify your code so that it uses Promise.all to collect all the promises into a single promise, which will resolve when all of the individual promises have resolved:

Promise.all(membersArray.map((member) => {
    return db
        .doneTodo
        .find({'victor._id': member._id})
        .then((userVictories) => ({
            email: member.email,
            victories: userVictories.length
        }));
})).then((memberStats) => {
    console.log(membersStats);
});

这篇关于NodeJS数组同步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆