簡體   English   中英

在for循環后同步運行Node js程序

[英]To run Node js program synchronously after for loop

我想在所有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)
}

您可能要使用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)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM