Array of promises [duplicate]

2019-03-03 23:16发布

This question already has an answer here:

I am working on a piece where I have to get json data from an API for different cities and build DOM.

So far, I have been able to do both. Only problem is that the API response time for the different cities are different. So, when I build the DOM they are not in the same order as I call the function. From what I recall I need to use promise to get it that order. My questions now are:

  1. How can I use an array of promises (since my input will vary).
  2. Also how do I execute an array of promises?

My working code so far:

var base_path = "https://www.example.com/";
var cities = [
   "San_Francisco",
    "Miami",
    "New_Orleans",
    "Chicago",
    "New_York_City"
];


function getData(city){
    var path =  base_path+city+".json";

    $.getJSON(path,function(data) {
     // build DOM
    });
}

for(var i=0;i<cities.length;i++) {
    getData(cities[i]);  
}

Thanks!

1条回答
贪生不怕死
2楼-- · 2019-03-03 23:40

This is fairly trivial to implement with Promise.all():

const base_path = "https://www.example.com/"
let cities = [
  "San_Francisco",
  "Miami",
  "New_Orleans",
  "Chicago",
  "New_York_City"
]

Promise.all(cities.map((city) => {
  return fetch(`${base_path}${city}.json`).then(res => res.json())
})).then((data) => {
  // Data is an array of all responses in the same order as the cities array
}).catch((err) => {
  // A request failed, handle the error
})

The reason the data array order is preserved is because Promise.all() preserves the same order that the original array of promises was in. The requests are executed in parallel. I used the Fetch API here instead of jQuery.

查看更多
登录 后发表回答