【发布时间】:2021-02-06 22:54:21
【问题描述】:
我已经为这个问题苦苦挣扎了一个星期,并且研究自己濒临死亡。我是一个完全的新手。我已经设法抓住了承诺的关键,但我没有看到如何将它包含在一个循环中。 我有一个正在查看数组的应用程序。针对 mongoose 数据库对阵列进行了一些验证(运行需要时间)。我正在尝试根据其中的一些验证将项目推送到新数组中。由于循环中的控制台日志,我知道验证正在工作。但是我的最终数组并没有等待循环完成。这意味着我需要将循环放入一个承诺中,或者我认为,但问题是我不知道如何解决它。当前输出是一个空白数组,而不是经过验证的数组。这是我的代码:
//dummy data of an array - this is originally extracted from a mongoose DB and works (it's my first promise).
const appArray = ["5f8f25d554f1e43f3089ea5d",
"5f8f25e854f1e43f3089ea5e",
"5f8f25f454f1e43f3089ea5f",
"5f8f314ab92c7f406f28b83a",
"5f8fe50a9d44694cad91a01b",
"5f92e8a75d848870e015dff3",
"5f92e8b35d848870e015dff4",
"5f92e8cb5d848870e015dff5",
"5f8fe51d9d44694cad91a01c"];
//the second promise takes the array above and validates it against another collection on mongoose
function myPromise2 (response){
return new Promise((resolve, reject) => {
let appoints = [];
response.forEach(e => {
//loop through each item of the array and look against Appointment collection
Appointment.findById(e, function(err, foundApp){
//some validation supposed to happen here and then pushed into a new array
appoints.push(foundApp);
console.log(appoints);
})
})
//once completed supposed to resolve and return
resolve(appoints);
})
};
myPromise2(appArray).then((response) => {console.log(response)});
【问题讨论】:
标签: javascript node.js arrays loops es6-promise