AngularJS:链接$ timeouts和Promises

时间:2016-12-19 23:37:45

标签: angularjs

我正在努力使用$ timeouts链接承诺。我希望有一个“$ timeout(myFunction,1000).then()”函数,只有当myFunction返回的所有链接超时都被解析时才会触发。

此代码段包含我尝试过的不同内容,我希望实现:

$timeout(myFunction,1000).then(function(myPromise) {
    console.log("I would like this message to appear when ALL chained promises are resolved, without knowing in advance how many chained promises there are. In this case this would be after 1500 ms, not 1000ms")
    myPromise.then(function()) {
        console.log("with this code patern I get a message after 1500ms, which is what I want, but this does not work anymore if myOtherFunction would return a third chained $timeout")
    }
})

myFunction = function() {
    console.log("hi, i am launching another timeout")
    return $timeout(myOtherFunction, 500)
}

myOtherFunction = function () {
    console.log("1500 ms have passed")
}

我该如何修复我的代码?谢谢!

2 个答案:

答案 0 :(得分:3)

返回对成功处理程序的承诺:

$timeout(null,1000).then(function() {
    console.log("It is 1000ms");
    var delay = 500
    return myPromise(delay);
 // ^^^^^^ return promise for chaining
}).then(function() {
    console.log("this happens after myPromise resolves");
});

function myPromise(delay) {
    promise = $timeout(null, delay);
    return promise;
});

因为调用promise的.then方法会返回一个新的派生promise,所以很容易创建一个promise链。可以创建任意长度的链和,因为承诺可以通过另一个承诺来解决(这将进一步推迟其解析),可以在任何点暂停/推迟承诺的解决。连锁,链条。这使得实现强大的API成为可能。

- AngularJS $q Service API Reference -- Chaining promises;

答案 1 :(得分:0)

受到georgeawg答案的启发,我创建了自定义超时函数,它返回fct返回的promise,而不是$ timeout返回的promise。我这样做是为了保持$ timeout语法。

vm.customTimeout = function (fct, timeout){
    return $timeout(fct, timeout).then(function(myReturnedPromise){
        return myReturnedPromise
    });
}

这个功能足以解决我上面的问题。我可以链接尽可能多的customTimeouts。

示例:

vm.customTimeout(myFunction,1000).then(function() {
    var activity1 = anyFunctionReturningAPromise(100);
    var activity2 = anyFunctionReturningAPromise(1000);
    return $q.all([activity1, activity2])
    console.log("Without knowing the content of myFunction, I am 100% sure that 
        every single chained promise retuned by myFunction is resolved before 
        executing this code, which is quite nice!")
}).then(function(){
    console.log("executes when customTimeout, activity1 & activity2 are all resolved.")
})

anyFunctionReturningAPromise = function(delay) {
    return vm.customTimeout(myFunction, delay)
}

随意评论您的想法。

我希望这对其他人有用:)