【发布时间】:2019-03-06 15:11:10
【问题描述】:
我认为我的问题在于 JS 的异步特性。我正在尝试将项目推送到数组中,但它似乎没有更新它......我在 for 循环中做了 console.log 语句,并看到它用数字填充数组,但是当我 console.log循环外的数组,我得到一个空数组。我正在使用猫鼬。 有什么建议吗?
代码如下:
let collections = [];
return Promise.all(courts.map(court => {
return new Promise((resolve, reject) => {
return Promise.all(court.users.map(async user => {
let tempPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 5000);
});
return SignDetail.find({
userName: user.userName,
signStatus: "signIn",
}).then(function(sign) {
if (user.userName.endsWith('zs')) {
let signCount = 0;
if (sign.length > 1) {
for (let j = 0; j < sign.length; j++) {
let courtObj = {courtName: sign[j].userName}; //make court object
signCount++; //increment each time there's a signature
if (j === sign.length - 1) { //only push object in array when all signatures have been counted
courtObj.signCount = signCount;
collections.push(courtObj);
console.log(collections)
}
}
}
} //end here
});
return tempPromise;
})).then(_ => resolve(collections));
})
})).then(collections => {
// HERE you will your collection and you can use this promise where this function is being called.
console.log(collections);
});
【问题讨论】:
标签: javascript mongoose