我的目标是从两个 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();
Requests
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);
});
// 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)