Grummle Grummle - 5 months ago 39
Node.js Question

While loop with promises

What would be the idiomatic way to do something like a while loop with promises. So:

do something
if the condition still stands do it again
repeat
then do something else.

dosomething.then(possilblydomoresomethings).then(finish)


I've done it this way I was wondering if there were any better/more idomatic ways?

var q = require('q');

var index = 1;

var useless = function(){
var currentIndex = index;
console.log(currentIndex)
var deferred = q.defer();
setTimeout(function(){
if(currentIndex > 10)
deferred.resolve(false);
else deferred.resolve(true);
},500);
return deferred.promise;
}

var control = function(cont){
var deferred = q.defer();
if(cont){
index = index + 1;
useless().then(control).then(function(){
deferred.resolve();
});
}
else deferred.resolve();
return deferred.promise;
}

var chain = useless().then(control).then(function(){console.log('done')});


Output:
1
2
3
4
5
6
7
8
9
10
11
done

Answer

I'd use an object to wrap the value. That way you can have a done property to let the loop know you're done.

// fn should return an object like
// {
//   done: false,
//   value: foo
// }
function loop(promise, fn) {
  return promise.then(fn).then(function (wrapper) {
    return !wrapper.done ? loop(Q(wrapper.value), fn) : wrapper.value;
  });
}

loop(Q.resolve(1), function (i) {
  console.log(i);
  return {
    done: i > 10,
    value: i++
  };
}).done(function () {
  console.log('done');
});