2017-10-08 59 views
0

我正在研究一个片段,我必须从不同城市的API获取json数据并构建DOM。数组承诺

到目前为止,我已经能够做到这一点。唯一的问题是不同城市的API响应时间不同。所以,当我构建DOM时,它们与我称之为函数的顺序不同。从我记得我需要使用诺言来得到它的顺序。 我现在的问题是:

  1. 如何使用承诺数组(因为我的输入会有所不同)。
  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]); 
} 

谢谢!

回答

2

这是相当琐碎与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()保持相同的顺序承诺的原阵列中的请求并行执行。我在这里使用了Fetch API而不是jQuery。

+0

请注意 - “如果任何传入的承诺被拒绝,Promise.all异步拒绝拒绝承诺的价值,而不管其他承诺是否已经解决。” – dimacpp