使用承诺的异步事件序列

Asynchronous sequence of events using promises

本文关键字:事件 异步 承诺      更新时间:2023-09-26

我是JavaScript新手,正在尝试理解如何编写一些代码,这些代码可以基于先前生成的输入列表的内容对两个第三方API进行异步调用。

一旦收集了所有的数据,我想创建一个图表。

我已经尝试了很多方法,但从我所读到的,使用承诺似乎是推荐的方法。我的大脑被拧成一团,首先使用传统的异步模型,然后试图理解承诺。

谁能给我指个正确的方向?
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;
    });
}));

edit:将解决方案更改为返回单个承诺