相关疑难解决方法(0)

将 Fetch API 与 Promise.all 结合使用

我的目标是从两个 URL 获取数据,并仅在两个 URL 均成功返回时才执行操作。另一方面,如果其中任何一个失败,我想返回错误。我已经尝试了我的代码并设法获得了预期的效果。

我的问题是,是否有更有效、更简洁的方法来实现相同的功能?

辅助函数

let status = (r) => {  
  if (r.ok) {  
    return Promise.resolve(r)  
  } else {  
    return Promise.reject(new Error(r.statusText))  
  }  
}

let json = (r) => r.json();
Run Code Online (Sandbox Code Playgroud)

要求

let urls = [
    'http://localhost:3000/incomplete',
    'http://localhost:3000/complete'
]

let promises = urls.map(url => {

    return fetch(url)  
    .then(status)  
    .then(json)  
    .then(d => Promise.resolve(d))
    .catch(e => Promise.reject(new Error(e)));

});

Promise.all(promises).then(d => {
    // do stuff with d
}).catch(e => {
    console.log('Whoops something went wrong!', e);
});
Run Code Online (Sandbox Code Playgroud)

javascript ajax ecmascript-6 es6-promise fetch-api

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

ajax ×1

ecmascript-6 ×1

es6-promise ×1

fetch-api ×1

javascript ×1