繁体   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