简体   繁体   English

使用诺言的异步事件序列

[英]Asynchronous sequence of events using promises

I am new to JavaScript and trying to understand how to write some code that makes a number of asynchronous calls to two third party API based on the contents of a previously generated input list. 我是JavaScript的新手,试图了解如何编写代码,这些代码根据先前生成的输入列表的内容对两个第三方API进行大量异步调用。

Once all the data has been collected, I want to create a chart. 收集完所有数据后,我想创建一个图表。

I have tried doing it a number of ways but from what I've read, using promises seems to be the recommended way. 我尝试了多种方法,但是从我读过的内容来看,使用Promise似乎是推荐的方法。 My brain is being twisted in knots, firstly using the traditional async model then trying to understand promises. 首先,使用传统的异步模型,然后尝试理解承诺,这使我的大脑陷入了混乱。

Can anyone point me in the right direction please? 谁能指出我正确的方向?

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.

The general pattern I use in cases like this is to push all of my promises into an array, then set up a promise action that gets all the returned values and does what I want (console.log is your friend to see how the data is returned): 在这种情况下,我使用的一般模式是将我所有的promise推送到一个数组中,然后设置一个promise操作,该操作将获取所有返回的值并执行我想要的操作(console.log是你的朋友,以查看数据如何回来):

Edit: country_data.get must return a promise object for this to work. 编辑: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
}

Warning: I normally work with jquery which uses slightly different syntax, and jsfiddle is down so this isn't fully tested. 警告:我通常会使用语法稍有不同的jquery,并且jsfiddle处于关闭状态,因此尚未完全测试。

Assuming CountryData#get and CityData#get return promises that resolve the requested country/city data, this is how I would handle this: 假设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: changed the solution to return a single promise 编辑:更改解决方案以返回单个承诺

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM