2016-03-04 115 views
0

我需要测试与REDIS(异步工作)如果一个值设置或让我的代码运行之前。虽然循环承诺,直到另一个承诺结束

我开始与循环无极工作,因为这里定义: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已在处理中,则需要等待直到timeline_id已从hashTest的Redis上删除。

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

回答

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