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

时间:2016-03-04 19:09:53

标签: javascript node.js redis promise q

如果在设置代码之前设置了值,我需要使用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已经在进行中,我需要等待UNTIL timeline_id已经从hashTest上删除了Redis。

我怎样才能确定我得到的结果而不是承诺状态来检查我是否仍然可以运行我的循环。

1 个答案:

答案 0 :(得分:1)

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

肯定不是很优雅,但我现在做得不好:

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() {    
...
}):