分别处理数组中的多个promise [英] Handling multiple promises within an array individually

查看:322
本文介绍了分别处理数组中的多个promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它可以对服务器进行Web服务调用,并返回一个Promise数组.

I have a function which makes web service calls to my server and returns an array of promises.

但是,其中一些呼叫可能有效,而其他呼叫则无效.我的函数的当前设置方式,如果其中之一失败,则会警告整个事件失败.如果我打了5个电话,其中1个可能会失败.我需要正确记录此信息,但不确定如何执行此操作.

However some of these calls might work while others might not. The way my function is currently set up, if one of them fails, it alerts that the entire thing failed. If I'm making 5 calls, 1 might fail. I need to log this correctly and I'm not sure how to do it.

理想的响应/日志将是:

An ideal response/log would be:

  1. 电话1已通过
  2. 电话2已通过
  3. 电话3已通过
  4. 呼叫4失败-原因
  5. 电话5已通过

现在,由于调用4失败,整个事件将返回句柄用户操作失败".

Right now the whole thing will return "The handle user operation failed" because call 4 failed.

功能:

var manageGroup = function (add, group, users){

    var deffered = $q.defer();
    var arrPromises = [];
    var promiseIndex = arrPromises.length;
    var usersLength = users.length;
    var operation = add ? "AddUserToGroup" : "RemoveUserFromGroup";
    var actionText = add ? "Added: " : "Removed: "
    var actionText2 = add ? " to " : " from "

    //Apply operation on selected groups
    for (var i = 0; i < usersLength; i++){
        arrPromises[i] = $().SPServices({
            operation: operation,
            groupName: group.name,
            userLoginName: users[i].domain
        });      
    }

    $q.all(arrPromises).then(
        function (){
            //when promises are finsihed
            for (var i = 0; i < usersLength; i++){
                console.log(actionText + users[i].name + actionText2  + group.name);
            };
            deffered.resolve();
        },
        //function incase of AJAX failure
        function (){
            alert('The handle user operation failed.');
        }
    ) 
    return deffered.promise;      
}

我试图单独处理承诺而不是使用$ q.all,但是现在日志中什么也没得到:

I tried to handle the promises individually instead of using the $q.all but now I'm not getting anything in the log:

我将本节内容删除:

/*$q.all(arrPromises).then(
    function (){
        //when promises are finsihed
        for (var i = 0; i < usersLength; i++){
            console.log(actionText + users[i].name + actionText2  + group.name);
        };
        deferred.resolve();
    },
    //function incase of AJAX failure
    function (){
        alert('The handle user operation failed.');
    }
) */

相反,它是这样引入的:

Introduced this instead:

for (var i = 0; i<promiseIndex; i++){
    arrPromises[i].then(
        function (){
            console.log(actionText + user[i].name + actionText2 + group.name);
        }
    ),
    function (){
        alert('Failed to add/remove'+  user[i].name + ' to ' + group.name)
    }
}

$q.all(arrPromises).then(function (){
    deferred.resolve();
}, function (){
    deferred.reject();
})

推荐答案

Q (在ng. $ q基于)或 bluebird 具有完全满足您需求的方法.

Q (on which ng.$q is based on) or bluebird have a method fulfilling exactly your needs.

对于蓝鸟,您将采用这种方式:

For bluebird, you'd go this way:

var Promise = require('bluebird');

Promise.settle(arrPromises).then(function(promises) {
    promises.forEach(function(p) {
        if (promise.isRejected()) {
            // it's a rejected promise.
        }
        else {
            // it's a resolved promise.
        }
    });
});

对于Q,您将采用这种方式:

And for Q, you'd go this way:

var Q = require('q');

Q.allSettled(arrPromises).then(function(promises) {
    promises.forEach(function(p) {
        if (p.state === 'fulfilled') {
            // it's a resolved promise.
        }
        else {
            // it's a rejected promise.
        }
    });
});

这两个库的优点是它们符合Promises/A +规范.这意味着您可以卸下ng.$ q,放其中之一,您当前的代码仍然可以使用.

The nice thing about both these libraries is that they're compliant with the Promises/A+ specification. Which means you can take off ng.$q, put one of these, and your current code will still work.

这篇关于分别处理数组中的多个promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆