在Promise.all

时间:2017-06-22 07:52:30

标签: javascript ajax ecmascript-6 es6-promise fetch-api

我的目标是从两个URL获取数据,并仅在两者成功返回时执行操作。另一方面,如果其中任何一个失败,我想返回一个错误。我玩过我的代码并设法获得理想的效果。

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

帮助程序功能

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

let json = (r) => r.json();

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);
});

3 个答案:

答案 0 :(得分:1)

使用 fetchOk 获取更好的错误消息,并destructuring访问结果:

<div id="div" style="white-space: pre;"></div>
{{1}}

答案 1 :(得分:0)

// 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>

答案 2 :(得分:0)

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)