簡體   English   中英

使用諾言的異步事件序列

[英]Asynchronous sequence of events using promises

我是JavaScript的新手,試圖了解如何編寫代碼,這些代碼根據先前生成的輸入列表的內容對兩個第三方API進行大量異步調用。

收集完所有數據后,我想創建一個圖表。

我嘗試了多種方法,但是從我讀過的內容來看,使用Promise似乎是推薦的方法。 首先,使用傳統的異步模型,然后嘗試理解承諾,這使我的大腦陷入了混亂。

誰能指出我正確的方向?

var countries = [];
// countries ends up with 10-30 country names in previous code    
var total_population = 0;
for(var n=0; n<countries.length; ++n) {
    var country_data=new CountryData();
    // async function that fetches country data
    country_data.get(countries[n]);
    country_data.onDone = function() {
        var capital=this.capital;
        var city_data=new CityData();
        // async function that fetches city data
        city_data.get(capital);
        city_data.onDone = function() {
            total_population += this.population;
        }
    }
}
// make a chart with total_population for example.

在這種情況下,我使用的一般模式是將我所有的promise推送到一個數組中,然后設置一個promise操作,該操作將獲取所有返回的值並執行我想要的操作(console.log是你的朋友,以查看數據如何回來):

編輯:country_data.get必須返回一個promise對象,此對象才能起作用。

var countries = ['US', 'CA', 'GB'];
var promises = [];
// countries ends up with 10-30 country names in previous code    
for(var n=0; n<countries.length; ++n) {
    var country_data=new CountryData();
    // async function that fetches country data and returns a promise
    promises.push(country_data.get(countries[n]));
}

//This will fire only once all async calls complete
Promise.all(promises).then(function(data) {
    console.log(data);
    //do stuff with data from all calls
}

警告:我通常會使用語法稍有不同的jquery,並且jsfiddle處於關閉狀態,因此尚未完全測試。

假設CountryData#get和CityData#get返回承諾可以解決請求的國家/城市數據,這就是我的處理方式:

var total_population = 0;

var promise = Promise.all(countries.map(function(country) {
  return new CountryData().get(country)
    .then(function(countryData) {
      return new CityData().get(countryData.capital);
    })
    .then(function(cityData) {
      total_population += cityData.population;
    });
}));

編輯:更改解決方案以返回單個承諾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM