假设我有一组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   

假设我想要等到所有这些都完成,不管是否有一个失败了。可能有一个资源的网络错误,我可以没有,但如果我能得到,我想在继续之前。我想优雅地处理网络故障。

因为承诺。所有这些都没有留下任何空间,在不使用承诺库的情况下,处理这个问题的推荐模式是什么?


当前回答

有一个完成的提议,一个函数,可以完成这个本机,在香草Javascript:承诺。allsettle已经进入了第4阶段,在ES2020中正式发布,并在所有现代环境中实现。它和另一个答案中的反射函数很相似。这里有一个例子,来自提案页面。以前,你必须这样做:

function reflect(promise) {
  return promise.then(
    (v) => {
      return { status: 'fulfilled', value: v };
    },
    (error) => {
      return { status: 'rejected', reason: error };
    }
  );
}

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.all(promises.map(reflect));
const successfulPromises = results.filter(p => p.status === 'fulfilled');

使用的承诺。取而代之的是,上述内容将等价于:

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
const successfulPromises = results.filter(p => p.status === 'fulfilled');

那些使用现代环境的人不需要任何库就可以使用这种方法。在这些情况下,下面的代码段应该可以正常运行:

Promise.allSettled ([ Promise.resolve (' a '), Promise.reject (b) ]) 不要犹豫(console.log);

输出:

[
  {
    "status": "fulfilled",
    "value": "a"
  },
  {
    "status": "rejected",
    "reason": "b"
  }
]

对于较老的浏览器,这里有一个符合规范的填充。

其他回答

类似的答案,但更适合ES6:

const a = Promise.resolve(1); const b =承诺。拒绝(新的错误(2)); const c = Promise.resolve(3); 的承诺。[a, b, c]。(p => p.catch(e => e))) .then(results => console.log(results)) // 1,错误:2,3 .catch(e => console.log(e)); const console = {log: msg => div.innerHTML += msg + "<br>"}; < div id = " div " > < / div >

根据返回值的类型,通常可以很容易地区分错误(例如,用undefined表示“don't care”,用typeof表示普通的非对象值,用result。result.toString(). startswith ("Error:")等

与其拒绝,不如用一个对象来解决。 当你实现承诺时,你可以这样做

Const promise = arg => { 返回新的承诺((resolve, reject) => { setTimeout(() => { 尝试{ If (arg != 2) 返回解析({success: true, data: arg}); 其他的 抛出新的错误(arg) }捕捉(e) { 返回解析({success: false, error: e, data: arg}) } }, 1000); }) } Promise.all([1、2、3、4、5)。Map (e => promise(e)))。然后(d => console.log(d))

本杰明的回答为解决这个问题提供了一个很好的抽象,但我希望有一个不那么抽象的解决方案。解决这个问题的显式方法是简单地对内部promise调用.catch,并从它们的回调返回错误。

let a = new Promise((res, rej) => res('Resolved!')),
    b = new Promise((res, rej) => rej('Rejected!')),
    c = a.catch(e => { console.log('"a" failed.'); return e; }),
    d = b.catch(e => { console.log('"b" failed.'); return e; });

Promise.all([c, d])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Promise.all([a.catch(e => e), b.catch(e => e)])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

更进一步,你可以写一个通用的catch处理程序,看起来像这样:

const catchHandler = error => ({ payload: error, resolved: false });

然后你就可以

> Promise.all([a, b].map(promise => promise.catch(catchHandler))
    .then(results => console.log(results))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!',  { payload: Promise, resolved: false } ]

这样做的问题是,被捕获的值将与未被捕获的值有不同的接口,所以要清理这个,你可以这样做:

const successHandler = result => ({ payload: result, resolved: true });

现在你可以这样做:

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

为了保持干燥,你看到了本杰明的答案:

const reflect = promise => promise
  .then(successHandler)
  .catch(catchHander)

现在是什么样子

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

第二种解决方案的优点是它是抽象的和DRY的。缺点是你有更多的代码,你必须记住反映你所有的承诺,使事情一致。

我将把我的解决方案描述为explicit和KISS,但确实不那么健壮。接口不能保证您确切地知道承诺是成功了还是失败了。

例如,你可以这样写:

const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));

这个不会被。catch抓到,所以

> Promise.all([a, b].map(promise => promise.catch(e => e))
    .then(results => console.log(results))
< [ Error, Error ]

没有办法判断哪个是致命的,哪个不是。如果这很重要,那么您将希望强制和接口跟踪它是否成功(这是reflect所做的)。

如果你只是想优雅地处理错误,那么你可以把错误视为未定义的值:

> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
    .then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]

在我的例子中,我不需要知道错误或它是如何失败的——我只关心是否有值。我将让生成承诺的函数负责记录特定的错误。

const apiMethod = () => fetch()
  .catch(error => {
    console.log(error.message);
    throw error;
  });

这样,应用程序的其余部分就可以忽略它的错误,并将其视为一个未定义的值。

我希望我的高级函数安全失败,而不担心它的依赖项失败的细节,当我必须做出权衡时,我也更喜欢KISS而不是DRY——这就是我最终选择不使用reflect的原因。

你可以通过同步执行器nsynjs按顺序执行你的逻辑。它将在每个承诺上暂停,等待解析/拒绝,并将解析的结果分配给data属性,或者抛出异常(用于处理您将需要try/catch块)。这里有一个例子:

function synchronousCode() { function myFetch(url) { try { return window.fetch(url).data; } catch (e) { return {status: 'failed:'+e}; }; }; var arr=[ myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"), myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js"), myFetch("https://ajax.NONEXISTANT123.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js") ]; console.log('array is ready:',arr[0].status,arr[1].status,arr[2].status); }; nsynjs.run(synchronousCode,{},function(){ console.log('done'); }); <script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>

从ES5开始,我一直在使用以下代码。

Promise.wait = function(promiseQueue){
    if( !Array.isArray(promiseQueue) ){
        return Promise.reject('Given parameter is not an array!');
    }

    if( promiseQueue.length === 0 ){
        return Promise.resolve([]);
    }

    return new Promise((resolve, reject) =>{
        let _pQueue=[], _rQueue=[], _readyCount=false;
        promiseQueue.forEach((_promise, idx) =>{
            // Create a status info object
            _rQueue.push({rejected:false, seq:idx, result:null});
            _pQueue.push(Promise.resolve(_promise));
        });

        _pQueue.forEach((_promise, idx)=>{
            let item = _rQueue[idx];
            _promise.then(
                (result)=>{
                    item.resolved = true;
                    item.result = result;
                },
                (error)=>{
                    item.resolved = false;
                    item.result = error;
                }
            ).then(()=>{
                _readyCount++;

                if ( _rQueue.length === _readyCount ) {
                    let result = true;
                    _rQueue.forEach((item)=>{result=result&&item.resolved;});
                    (result?resolve:reject)(_rQueue);
                }
            });
        });
    });
};

用法签名就像Promise.all。主要的区别在于《承诺》。等待会等待所有的承诺来完成自己的工作。