我现在正在this b地摇头,但我无法解决这个问题。 从Module_A我使用promises调用Module_B中的方法。在这个方法中,我使用嵌套的每个循环,我有一个问题,使用正确的语法。
我试图打破这个。在此示例中,数组locations []始终为空,我无法将其解析为Module_A。
Module_A:
app.listen(server_connection.port, () => {
console.log('Server started on port ' + server_connection.port);
getRegions() // This works
.then(function(response){
return constructionsiteParser.constructionsiteParser(response); // here is the problem to receive the array from Module_B
})
.then(function(locations){
console.log(locations.length);
})
.catch(function(msg){
console.error(msg);
});
});
Module_B:
var locations = [];
exports.constructionsiteParser = function constructionsiteParser(xmlArr){
var promise = new Promise (function(resolve, reject){
getLocations(xmlArr)
.then(function(locations){
console.log(locations); //locations is empty and can't resolve it to Module_A
if(objArr > 0){
resolve(locations);
}else{
reject("Locations array is empty");
}
})
});
return promise;
}
let getLocations = function(xmlArr){
return new Promise(function(resolve, reject){
var $ = cheerio.load(xmlArr[0]);
$('situation').each( function(){
parseImportantInfos($, this)
.then(function(obj){
locations.push(obj);
})
});
resolve(locations); // the problem must be somewhere here. This resolve will be executed bevor the eachloop from above is done
})
}
let parseImportantInfos = function($, record){
return new Promise (function(resolve, reject){
$(record).find('situationRecord').each( function(i){
//do some stuff
if(startLocationCode != '' && endLocationCode != '' ){
Promise.all([
//do some stuff
])
.then( values =>{
// do some stuff
})
.then(function(obj){
resolve(obj);
})
.catch((err) =>{
reject("There was an error while parsing the xml");
console.log('err', err.stack);
});
}
});
});
};
我想要的是将完整的位置数组返回给Module_A
答案 0 :(得分:1)
而不是
let getLocations = function(xmlArr){
return new Promise(function(resolve, reject){
var $ = cheerio.load(xmlArr);
$('situation').each( function(){
parseImportantInfos($, this)
.then(function(obj){
locations.push(obj);
})
});
resolve(locations); // the problem must be somewhere here. This resolve will be executed bevor the eachloop from above is done
})
}
你想要使用像
这样的东西let getLocations = function(xmlArr){
return new Promise(function(resolve, reject){
var $ = cheerio.load(xmlArr);
var promiseList = [];
$('situation').each( function(){
var newPromise = parseImportantInfos($, this)
.then(function(obj){
locations.push(obj);
})
promiseList.push(newPromise)
});
Promise.all(promiseList).then(function(){
resolve(locations);
})
})
}