Array of promises [duplicate]

天涯浪子 提交于 2019-12-20 06:04:57

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!