GroovyDotCom February 2016

resolve values in a Promise While Loop

I found: Correct way to write loops for promise. and While loop using bluebird promises

However when I try to use these to loop a promise, the resolve value of that promise is not passed down the chain.

For example, the following code prints:

did it 1 times
did it 2 times
undefined <-- this should be hello world

var Promise = require('bluebird');

var times = 0;

var do_it = function(o) {
    return new Promise(function(resolve, reject) {
        setTimeout(function () {
            console.log("did it %d times", ++times);
            resolve(o);
        }, 1000);
    });
}

var promiseWhile = Promise.method(function(condition, action) {
    if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

var do_it_twice = function(o) {
    return promiseWhile(
        function() { return times < 2; },
        function() { return do_it(o);  }
    );
}

do_it_twice("hello world").then(function(o) {console.log(o)});

Answers


Alexey B. February 2016

You need to specify returned value

var promiseWhile = Promise.method(function(condition, action, result) {
    if (!condition()) return result;
    return action().then(promiseWhile.bind(null, condition, action, result));
});

var do_it_twice = function(o) {
    return promiseWhile(
        function() { return times < 2; },
        function() { return do_it(o);  },
        o
    );
}

Post Status

Asked in February 2016
Viewed 3,762 times
Voted 4
Answered 1 times

Search




Leave an answer