Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - 等到所有诺言都完成,即使有些诺言被拒绝(Wait until all promises complete even if some rejected)

Let's say I have a set of Promise s that are making network requests, of which one will fail:(假设我有一组Promise正在发出网络请求,其中一个会失败:)

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

Let's say I want to wait until all of these have finished, regardless of if one has failed.(假设我想等到所有这些完成为止,无论是否失败。)

There might be a network error for a resource that I can live without, but which if I can get, I want before I proceed.(我可能无法使用的资源可能会出现网络错误,但是如果可以得到,我会在继续之前希望这样做。) I want to handle network failures gracefully.(我想优雅地处理网络故障。)

Since Promises.all doesn't leave any room for this, what is the recommended pattern for handling this, without using a promises library?(由于Promises.all对此没有任何余地,因此在不使用promises库的情况下,推荐的处理方式是什么?)

  ask by Nathan Hagen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, you just need a reflect :(当然,您只需要reflect :)

const reflect = p => p.then(v => ({v, status: "fulfilled" }),
                            e => ({e, status: "rejected" }));

reflect(promise).then((v => {
    console.log(v.status);
});

Or with ES5:(或使用ES5:)

function reflect(promise){
    return promise.then(function(v){ return {v:v, status: "fulfilled" }},
                        function(e){ return {e:e, status: "rejected" }});
}


reflect(promise).then(function(v){
    console.log(v.status);
});

Or in your example:(或在您的示例中:)

var arr = [ fetch('index.html'), fetch('http://does-not-exist') ]

Promise.all(arr.map(reflect)).then(function(results){
    var success = results.filter(x => x.status === "fulfilled");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...