等待所有响应,然后调用该函数

问题描述 投票:0回答:3

我有多个 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()
,但我不知道在哪里做。

javascript promise
3个回答
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
投票

您真的不需要另一个

Promise.all
。只需将主体解析和属性提取承诺链接到您已有的
map
回调中即可:

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

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

1
投票

尝试使用与 URL 相同的技巧。只需获取每个响应,将其映射到您想要的内容,然后将所有内容放入

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.