gpt4 book ai didi

javascript - Node js 同步每个循环

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:16 25 4
gpt4 key购买 nike

在我的 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); 始终打印 0console.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com