假设我有一组承诺正在发出网络请求,其中一个会失败:
// http://does-not-exist will throw a TypeError
var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]
Promise.all(arr)
.then(res => console.log('success', res))
.catch(err => console.log('error', err)) // This is executed
Run Code Online (Sandbox Code Playgroud)
让我们说我想等到所有这些都结束了,不管一个人是否失败了.对于我可以没有的资源,可能存在网络错误,但如果我可以获得,我希望在继续之前.我想优雅地处理网络故障.
既然Promise没有留下任何空间,那么在不使用promises库的情况下,处理此问题的推荐模式是什么?
而所有Promise.all关于如何等待所有承诺的问题,但我想走另一条路——当任何承诺失败时,停止其他承诺,甚至停止整个脚本。
这是一个简短的例子来说明:
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'resolve1');
}).then(a => { console.log('then1'); return a; });
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 2000, 'reject2');
}).then(a => { console.log('then2'); return a; });
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 3000, 'resolve3');
}).then(a => { console.log('then3'); return a; });
Promise.all([promise1, promise2, promise3])
.then(values => { console.log('then', values); })
.catch(err => { console.log('catch', err); throw err; });
// results:
// …Run Code Online (Sandbox Code Playgroud)