What happens with $q.all() when some calls work and others fail?

后端 未结 7 1587
生来不讨喜
生来不讨喜 2020-11-30 03:09

What happens with $q.all() when some calls work and others fail?

I have the following code:

    var entityIdColumn = $scope.entityType.toLowerCase()          


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 03:27

    It's been a while since this question was posted, but maybe my answer might still help someone. I solved a similar problem on my end by simply resolving all promises, but with a return I could process later and see if there were any errors. Here's my example used to preload some image assets:

    var loadImg = function(imageSrc) {
        var deferred = $q.defer();
    
        var img = new Image();
        img.onload = function() {
            deferred.resolve({
                success: true,
                imgUrl: imageSrc
            });
        };
        img.onerror = img.onabort = function() {
            deferred.resolve({
                success: false,
                imgUrl: imageSrc
            });
        };
        img.src = imageSrc;
    
        return deferred.promise;
    }
    

    Later I can see which ones are errorious:

    var promiseList = [];
    for (var i = 0; i < myImageList.length; i++) {
        promiseList[i] = loadImg(myImageList[i]);
    }
    $q.all(promiseList).then(
        function(results) {
            for (var i = 0; i < results.length; i++) {
                if (!results[i].success) {
                    // these are errors
                }
            }
        }
    );
    

提交回复
热议问题