2016-03-04 117 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() {  
... 
}):