[英]To run Node js program synchronously after for loop
i want to execute the last console statement
after all the for loop
execution, but that console statement executes immediately
when control enters else
statement, please help me to solve this issue 我想在所有
for loop
执行之后执行最后一个console statement
,但是当控制进入else
语句时,该console语句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)
}
You might want to use Promise.all([]).then()
. 您可能要使用
Promise.all([]).then()
。
EDIT: example with your specific problem 编辑:与您的特定问题的示例
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)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.