一系列的承诺 [英] Array of promises

查看:99
本文介绍了一系列的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个我必须从不同城市的API获取json数据并构建DOM的文章。

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

到目前为止,我已经能够做到这两点。唯一的问题是不同城市的API响应时间不同。因此,当我构建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. 我如何使用一系列承诺(因为我的输入会有所不同)。

  2. 另外我如何执行一系列承诺?

到目前为止我的工作代码:

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]);  
}

谢谢!

推荐答案

使用 Promise.all()实现这一点非常简单:

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
})

数据的原因保留数组顺序是因为 Promise.all()保留了原始promises数组所在的顺序。请求是并行执行的。我在这里使用了 Fetch API 而不是jQuery。

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.

这篇关于一系列的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆