Using Fetch API with Promise.all

可紊 提交于 2019-12-04 16:53:20

Use fetchOk for nicer error messages, and destructuring to access the results:

let fetchOk = (...args) => fetch(...args)
  .then(res => res.ok ? res : res.json().then(data => {
    throw Object.assign(new Error(data.error_message), {name: res.statusText});
  }));

Promise.all([
  'http://localhost:3000/incomplete',
  'http://localhost:3000/complete'
].map(url => fetchOk(url).then(r => r.json()))).then(([d1, d2]) => {
  // do stuff with d1 and d2
}).catch(e => console.error(e));


// Work around stackoverflow's broken error logger.
var console = { error: msg => div.innerHTML += msg + "<br>" };
<div id="div" style="white-space: pre;"></div>

// 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);
})
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
foundling
const urls = [
    'http://localhost:3000/incomplete',
    'http://localhost:3000/complete'
]
const json = (r) => r.json()
const status = (r) => r.ok ? Promise.resolve(r) : Promise.reject(new Error(r.statusText))
const toRequest = url => fetch(url).then(status).then(json)
const onError = e => { console.log('Whoops something went wrong!', e) }
const consumeData = data => { console.log('data: ', data) }

Promise.all(urls.map(toRequest))
  .then(consumeData)
  .catch(onError)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!