AngularJS: $q wait for all even when 1 rejected

后端 未结 8 1594
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 16:23

I\'ve been trying to wait for a couple of promises with Angular\'s $q but there seems to be no option to \'wait for all even when a promis is rejected\'. I\'ve created an exampl

8条回答
  •  逝去的感伤
    2021-02-01 17:14

    A simple solution would be to use catch() to handle any errors and stop rejections from propagating. You could do this by either not returning a value from catch() or by resolving using the error response and then handling errors in all(). This way $q.all() will always be executed. I've updated the fiddle with a very simple example: http://jsfiddle.net/pHEf9/125/

    ...
    function handleError(response) {
        console.log('Handle error');
    }
    
    // Create 5 promises
    var promises = [];
    var names = [];
    for (var i = 1; i <= 5; i++) {
        var willSucceed = true;
        if (i == 2) willSucceed = false;
        promises.push(
          createPromise('Promise' + i, i, willSucceed).catch(handleError));
    }
    ...
    

    Be aware that if you don't return a value from within catch(), the array of resolved promises passed to all() will contain undefined for those errored elements.

提交回复
热议问题