我在使数组工作时遇到麻烦,就像我在函数后执行console.log语句时那样,我得到一个空数组...我知道它与JS的异步特性有关,但是我可以不知道如何解决它。我尝试使用Promises,但是console.log语句中仍然出现空数组。同样,总变量即使应增加也保持等于0。
有任何提示/建议吗?谢谢。
这是我的代码:
let total = 0;
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);
}
}
}
} //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);
});
test() //call async function
courts.forEach(court => { // count amount of signatures for only zs courts
for (let i = 0; i < court.users.length; i++) {
SignDetail.countDocuments({userName: court.users[i].userName},
function(err, count) {
if (count > 0) total = count;
});
}
});
console.log(total) // output should be greater than 0, but console outputs 0
console.log(collections); //outputs []
}