等待所有回复,然后调用函数

时间:2018-02-23 02:03:40

标签: javascript api promise fetch

我有多个URL来调用数据,我希望在它们全部响应并且已经收到数据后调用一个函数。

var promises = urls.map(url => fetch(url));

Promise.all(promises).then(response => {
 for (var i = 0; i < response.length; i++) {
  response[i].json().then(data => { dataReceived.push(data.rows)})
 }
 }).then(dataReceived=> {

  doThisFucntion(withAllTheData);

 });

我确定我只需要添加另一个promise.all(),但我不知道该怎么做。

由于

3 个答案:

答案 0 :(得分:2)

可能是这样的:

var promises = urls.map(url => fetch(url));

Promise.all(promises)
  .then(response => Promise.all(response.map(resp=>resp.json())))
  .then(data=>data.map(element=>element.rows))
  .then(dataReceived=> {    
    doThisFucntion(withAllTheData);
  });

答案 1 :(得分:1)

尝试使用您用于网址的相同技巧。只需获取每个回复,将其映射到您想要的内容,然后将其全部放在Promise.all

var promises = urls.map(url => fetch(url));

Promise.all(promises).then(response => {
    return Promise.all(response.map(resp => resp.json().then(data => data.rows)));
}).then(dataReceived => {
    // dataReceived is an array where each entry is one of the 'data.rows' from before.
    doThisFucntion(dataReceived);
});

答案 2 :(得分:1)

你真的不需要另一个Promise.all。只需将正文解析和属性提取承诺链接到您已经拥有的map回调中:

var promises = urls.map(url =>
  fetch(url).then(response => response.json()).then(data => data.rows)
);

Promise.all(promises).then(doThisFunction);