![](/img/trans.png)
[英]How can I wait for multiple promises to all be done before using their return data for another function call?
[英]How to wait for all promises to be done then do an action?
我有一系列的承諾,我使用$ q.all來執行所有的承諾,然后我做了一個動作,不知怎的,這個動作在承諾給出回答之前執行。
注意:flightAPIService.getNearestAirports()返回$ http angular:
this.getNearestAirports = function (dataObj) {
console.log('Client::flight service:: get the nearest '+ dataObj.maxAirports+' airport for lat: '+dataObj.lat+'lng:'+dataObj.lng);
return $http.post('/getNearestAirports', dataObj);
//// the result return in JSON format (Server converted the response from XML to JSON)
//answer looks like:
//{"airportResponse":{"$":{"authorisedAPI":"true","processingDurationMillis":"119","success":"true"},"airports":[{"airports":[{"$":{"city":"Tel-aviv","country":"Israel","lat":"32.011389","lng":"34.886667","name":"Ben Gurion","timezone":"Asia/Jerusalem"},"code":["TLV"]}]}]}}
};
當$ q.all執行promises(airportPromises)時,我預計在承諾准備就緒之后打印表對象,但實際上在promise之前打印的表已經回答:
$q.all(airportPromises).finally(function(res){
//return callback(null, table);
console.log(table);
},function(err){
callback(err);
return console.error('one promise error',err);
})
這里所有的代碼:
this.addAirportsToTable = function (table,callback) {
var airportPromises = [];
// var defered = $q.defer();
this.whenFlightNeeded(table).then(function (result) {
var table = result;
for (let dayIndex = 0; dayIndex < table.length; dayIndex++) {
if (table[dayIndex].flight.flight) {
var origin = {
maxAirports: 3,
lat: table[dayIndex]['cityGoogleInf'][0].latitude,
lng: table[dayIndex]['cityGoogleInf'][0].longitude
};
var dist = {
maxAirports: 3,
lat: table[dayIndex + 1]['cityGoogleInf'][0].latitude,
lng: table[dayIndex + 1]['cityGoogleInf'][0].longitude
};
var promise1 = flightAPIService.getNearestAirports(origin).then(function (resultOriginAirport) {
table[dayIndex]['flight'].airport.push(resultOriginAirport.data);
});
var promise2 = flightAPIService.getNearestAirports(dist).then(function (resultDistAirport) {
table[dayIndex + 1]['flight'].airport.push(resultDistAirport.data);
});
airportPromises.concat([promise1,promise2]);
}
}
$q.all(airportPromises).finally(function(res){
//return callback(null, table);
console.log(table);
},function(err){
callback(err);
return console.error('one promise error',err);
})
});
//return defered.promise;
}
知道如何確保所有承諾都完成然后打印表嗎?
我相信問題是你的concat
。
concat
不會修改現有數組,但會返回一個新數組。 所以你調用$q.all
傳遞一個空數組因此立即解析。
來自MDN :
注意:連接數組/值將使原始文件不受影響。 此外,對新陣列的任何操作都不會對原始陣列產生任何影響,反之亦然。
快速示例: https : //jsfiddle.net/bunc6zg9/
另一方面, $q.all
解析了其等待的promises值的數組。 因此,如果您從兩個承諾中返回.then
的表值,那么您可以在$.all
構建表。 這樣,您的包含其狀態的保證鏈就沒有變量全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.