简体   繁体   中英

While loop in promise until another promise ends

I need to test with REDIS (which work asynchronously) if a value is set or not before letting my code to run.

I started to work with Loop Promise as defined here : https://stackoverflow.com/a/17238793/3912805

I've tried this but unfortunately I'm stuck with a promise in pending :

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...
});

I need to check in intervals, cause if a timeline_id is already in process, I need to wait UNTIL timeline_id has been removed on Redis from hashTest.

How can I be sure I got result rather than promise state to check if I can still run my loop or not.

Finally, I found a way to achieve this...

for sure not really elegant, but I can't do better for now :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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