【问题标题】:To run Node js program synchronously after for loop在for循环之后同步运行Node js程序
【发布时间】:2018-11-24 05:27:35
【问题描述】:

我想在所有for loop执行之后执行最后一个console statement,但是当控制进入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)
}

【问题讨论】:

  • 你可以使用async.eachSeries() of async library。
  • @AnkitAgarwal 有没有其他方法可以在不使用任何库的情况下完成这项工作?

标签: javascript node.js asynchronous promise synchronization


【解决方案1】:

您可能想使用Promise.all([]).then()

the docs

编辑:具体问题的示例

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)
})

【讨论】:

  • 非常感谢......你能告诉我这条线是做什么的promises.push(promise)
  • 您所做的是将您的承诺push 放在一个数组中。 Promise.all 将创建一个新的 Promise,当所有 Promise(在数组 promises 中)都被解决时,该 Promise 将被解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多