This question already has an answer here:
- Promise.all().then() resolve? 1 answer
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:
- How can I use an array of promises (since my input will vary).
- 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!
This is fairly trivial to implement with
Promise.all()
:The reason the
data
array order is preserved is becausePromise.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.