问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/46626610/array-of-promises