将 Fetch API 与 Promise.all 结合使用

Sam*_*uel 3 javascript ajax ecmascript-6 es6-promise fetch-api

我的目标是从两个 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)

Ton*_*gan 5

// https://jsonplaceholder.typicode.com - Provides test JSON data
var urls = [
  'https://jsonplaceholder.typicode.com/todos/1',
  'https://jsonplaceholder.typicode.com/todos/2',
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2'
];

// Maps each URL into a fetch() Promise
var requests = urls.map(function(url){
  return fetch(url)
  .then(function(response) {
    // throw "uh oh!";  - test a failure
    return response.json();
  })  
});

// Resolve all the promises
Promise.all(requests)
.then((results) => {
  console.log(JSON.stringify(results, null, 2));
}).catch(function(err) {
  console.log("returns just the 1st failure ...");
  console.log(err);
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Run Code Online (Sandbox Code Playgroud)