在我的節點JS後端我運行這個方法。節點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", situation.length);
底部版畫始終爲0 也console.log(locations)
是空
這是日誌的一部分:
...
from outter 0
from outter 0
from outter 0
from outter 0
from outter 0
[]
before push []
after push [....
我想這是因爲節點服務器運行在每個內部循環完成之前的底部。所以我想讓它更時尚。我想要做的是這樣的:
outer each{
//run this first
inner each{
.....
}
//if inner each is done run this
if(...){}
}
但我不知道如何把這個在正確的語法。 我已經嘗試過嵌套Promise,但它不起作用。