javascript - 一系列的 promise

标签 javascript jquery asynchronous promise closures

我正在开发一个项目,我必须从不同城市的 API 获取 json 数据并构建 DOM。

到目前为止,我已经能够做到这两点了。唯一的问题是不同城市的API响应时间不同。因此,当我构建 DOM 时,它们的顺序与我调用函数的顺序不同。据我记得,我需要使用 Promise 来获得该订单。 我现在的问题是:

  1. 我如何使用一系列 promise (因为我的输入会有所不同)。
  2. 另外,我如何执行一系列 promise ?

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

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() 实现这一点相当简单:

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

保留 data 数组顺序的原因是 Promise.all() 保留与原始 Promise 数组相同的顺序。请求在以下位置执行平行线。我用了Fetch API这里而不是 jQuery。

关于javascript - 一系列的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626610/

相关文章:

javascript - 如何在 Angular Js 中制作粘性标题?

javascript - 单击后输入文本返回默认值

javascript - 使用 jQuery 输出彼此相邻的同级 div

c# - 如何在 C# 中的 GUI 线程上启动一系列定时事件?

java - 异步 API 性能更差

javascript - 如何从数组中选择两个 div 元素并对其执行函数?

jquery - 如何使用 jQuery 或 PHP 每 3 分钟异步保存一次数据

javascript - $(window).width() 在 IE9 中不工作

c# - .NET Socket ReadAsync 在写循环 Async/Await 期间被阻塞

javascript - jquery 类型错误 : can't assign to properties of new String