承诺链(angular javascript)

Promise chaining (angular javascript)

所以我有几个函数都对服务进行异步调用。我不希望他们都在前一个完成后执行,但前提是前一个没有失败。它看起来像这样:

var fn1 = function() {
    var promise = aService.fn1();
    var successCallback = function(response) {
        return true;
    };
    var errorCallback = function() {
        return false;
    };
    return promise.then(successCallback, errorCallback);
};
var fn2 = function() {
    var promise = aService.fn2();
    var successCallback = function(response) {
        return true;
    };
    var errorCallback = function() {
        return false;
    };
    return promise.then(successCallback, errorCallback);
};
var fn3 = function() {
    var promise = aService.fn3();
    var successCallback = function(response) {
        return true;
    };
    var errorCallback = function() {
        return false;
    };
    return promise.then(successCallback, errorCallback);
};

fn1().then(function(resp){
    if (resp)
    {
        fn2().then(function(resp){
            if (resp)
            {
                fn3().then(function(resp){
                    if (resp)
                    {
                        // all functions have been called in order were successful
                    }
                });
            }
        });
    }
});

添加到这个链中的函数越多,最后的执行看起来就越糟糕。我想知道是否有另一种方法可以构造它,使其表现相同但不会创建巨大的链式异步调用树。如果我能把它保持在同一个缩进上,那就太好了。谢谢!

如果你的服务功能已经被承诺,你可以让事情变得非常简短:

aService.fn1()
.then(aService.fn2.bind(aService))
.then(aService.fn3.bind(aService))
.then(function(){
    // all functions have been called in order and were successful
});

您必须将错误回调修改为 return $q.reject() 而不是 false,即:

var fn1 = function() {
    var promise = aService.fn1();
    var successCallback = function(response) {
        // no return needed, unless the next stage
        // requires the results of this stage
    };
    var errorCallback = function() {
        return $q.reject();
    };
    return promise.then(successCallback, errorCallback);
};

链接变为:

fn1()
    .then(function() {
        return fn2();
    })
    .then(function() {
        return fn3();
    })
    .then(function() {
        // ALL SUCCEEDED HERE
    });

事实上,您甚至不必在 f1f2f3 中编写那些痛苦的代码,即以下内容也可以完成工作:

aService.fn1()
    .then(function() {
        return aService.fn2();
    })
    .then(function() {
        return aService.fn3();
    })
    .then(function() {
        // ALL SUCCEEDED HERE
    });