承诺数组
我正在开发一个部分,我必须从不同城市的API获取json数据并构建DOM。
到目前为止,我已经能够做到这两点。 唯一的问题是不同城市的API响应时间不同。 所以,当我构建DOM时,它们与我调用函数的顺序不同。 从我记得我需要使用诺言来获得它的顺序。 我现在的问题是:
- 我怎样才能使用一系列承诺(因为我的输入会有所不同)。
- 另外我如何执行一系列承诺?
到目前为止我的工作代码:
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()
保留了与原始promises数组相同的顺序。请求是并行执行的。 我在这里使用了Fetch API而不是jQuery。