Array of promises [duplicate]

余生颓废 提交于 2019-12-02 08:32:32

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.

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