javascript - Node js 同步每个循环

标签 javascript node.js foreach synchronization

在我的 Node JS 后端运行这个方法。

var locations = [];

exports.constructionsiteParser = function constructionsiteParser(response){
    var timestamp = new Date().toDateInputValue();
    const $ = cheerio.load(response);
    $('situation').each( function(){
    var situation = [];
        $(this).find('situationRecord').each( function(i){
          var startLocationCode = $(this).find('alertCMethod2SecondaryPointLocation').find('specificLocation').text();
      var endLocationCode = $(this).find('alertCMethod2PrimaryPointLocation').find('specificLocation').text();
      var overallStartTime = $(this).find('overallStartTime').text();
      var overallEndTime = $(this).find('overallEndTime').text();
      if((startLocationCode != '') && new Date(timestamp) >= new Date(overallStartTime) && new Date(timestamp) <= new Date(overallEndTime) ){
        Promise.all([
          locationCodeToGeodataRequst.geodataByLocationcode(startLocationCode), 
          locationCodeToGeodataRequst.geodataByLocationcode(endLocationCode) 
        ]).then( values =>{
          return createSituationRecord($, this, startLocationCode, endLocationCode, values[0], values[1]);
        }).then( function(obj){
          console.log("before push", situation);
          situation.push(obj);
          console.log("after push", situation);
          return situation;
        }, handleError);
      }
    })
    console.log("from outter", situation.length);
    if(situation.length > 0){ //if situation is not empty
      locations.push(situation);
    }
   })
        console.log(locations);
  }

底部的 console.log("from outter",情况.length); 始终打印 0 console.log(locations) 也是空的

这是日志的一部分:

...
from outter 0
from outter 0
from outter 0
from outter 0
from outter 0
[]
before push []
after push [....

我认为发生这种情况是因为 Node 服务器在内部每个循环完成之前运行底部部分。所以我想让它更加同步。我想做的是这样的:

outer each{

  //run this first
  inner each{
  .....
  }

  //if inner each is done run this
  if(...){}

}

但我不知道如何将其放入正确的语法中。 我已经尝试过使用嵌套 Promise 但它不起作用。

最佳答案

你可以返回这个 promise 。向调用者处理

关于javascript - Node js 同步每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46705000/

相关文章:

javascript - 将 SELECT 同步到 Web sql

javascript - Coffeescript 和 nodeJS 中的常量

Windows USB 端口 'address'

node.js - findByIdAndUpdate 的一致预保存验证

c# - C# 在 foreach 中重用变量是否有原因?

c# - 如何从对象中仅获取 1 行

C# 对于表中的每个循环?

javascript - 更改按钮功能时出现未捕获的引用错误

javascript - 如何在嵌套 div 上使用 .click

javascript - 图像未完全显示在网站上,导致服务器崩溃