我想在执行完所有的console statement之后执行最后一个for loop,但是当控制进入else语句时,控制台语句executes immediately,请帮助我解决这个问题。
if (false) {
//
} else {
//pushing the scenarios object id from project table to scenarios array
// function async(project) {
// Promise((resolve, reject) => {
for (i = 0; i < projectToBeDeleted[0].scenarios.length; i++) {
scenarios.push(projectToBeDeleted[0].scenarios[i])
}
//iterating the scenario table to get the child scenarios from all matching scenarios
for (i = 0; i < scenarios.length; i++) {
query = { "_id": scenarios[i] }
Scenario.getScenarios(query)
.then((scenariosResponse) => {
for (j = 0; j < scenariosResponse[0].childScenario.length; j++) {
scenarios.push(scenariosResponse[0].childScenario[j])
}
})
.catch((error) => {
res.status(400).send({
message: error.stack
})
})
}
// })
console.log("sync", scenarios)
}发布于 2018-06-14 12:32:14
您可能需要使用Promise.all([]).then()。
见医生们。
编辑:使用特定问题的示例
for (i = 0; i < projectToBeDeleted[0].scenarios.length; i++) {
scenarios.push(projectToBeDeleted[0].scenarios[i]);
}
const promises = [];
for (i = 0; i < scenarios.length; i++) {
const query = { "_id": scenarios[i] }
const promise = Scenario.getScenarios(query)
.then((scenariosResponse) => {
for (j = 0; j < scenariosResponse[0].childScenario.length; j++) {
scenarios.push(scenariosResponse[0].childScenario[j])
}
})
.catch((error) => {
res.status(400)
.send({
message: error.stack
})
})
promises.push(promise);
}
Promise.all(promises).then(() => {
console.log("sync", scenarios)
})https://stackoverflow.com/questions/50857421
复制相似问题