我有多个 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()
,但我不知道在哪里做。
可能是这样的:
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);
});
您真的不需要另一个
Promise.all
。只需将主体解析和属性提取承诺链接到您已有的 map
回调中即可:
var promises = urls.map(url =>
fetch(url).then(response => response.json()).then(data => data.rows)
);
Promise.all(promises).then(doThisFunction);
尝试使用与 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);
});