繁体   English   中英

在承诺中循环直到另一个承诺结束

[英]While loop in promise until another promise ends

在让我的代码运行之前,我需要使用REDIS(异步工作)进行测试(是否设置了值)。

我开始按如下定义使用Loop Promise: https : //stackoverflow.com/a/17238793/3912805

我已经尝试过了,但是不幸的是我在等待中坚持了一个承诺:

promise: { state: 'pending' }

function promiseWhile(condition, body) {
    var done = Q.defer();

    function loop() {
        /** When the result of calling condition is no longer true, we are done */
        if(!condition())
            return done.resolve();
        /** Use 'when', in case `body` does not return a promise */
        /** When it completes loop again otherwise, if it fails, reject the done promise */
        Q.when(body(), loop, done.reject);
    }
    /** Start running the loop in the next tick so that this function is completely async */
    /** It would be unexpected if body was called synchronously the first time */
    Q.nextTick(loop);
    return done.promise;
}

var timeline_id = 3;    
promiseWhile(function () {          
    return Q.ninvoke(redisClient, 'hget', 'hashTest', timeline_id).then(function (result) {
        console.log(result + '<---->');
        return result;
    });
}, function () {
    return Q.delay(500);
}).then(function () {
    // Let's continue process...
});

我需要检查间隔,因为如果timeline_id已经在处理中,我需要等待从hashTest在Redis上删除的UNTIL timeline_id。

我如何确定得到结果而不是诺言状态,以检查是否仍然可以运行循环。

最后,我找到了实现此目标的方法...

当然不是很优雅,但是我现在不能做得更好:

var redisState = true;
promiseWhile(function () {
    /** Loop until true */
    return redisState;
}, function (result) {
    return Q.ninvoke(redisClient, 'HGET', 'hashTest', timeline_id).then(function(result) {
        redisState = result;
        if (redisState) {
            redisState = result;
            return Q.delay(500);                
        }
    });
}).then(function() {    
...
}):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM