0

There seem to be many answers to questions on how to use bluebird promises to call asynchronous functions from a for / while loop, but as far as I can see, all require node.js to work (e.g. promise.method() or process.nextTick() ; e.g. such as: While loop using bluebird promises ). Is there any way to do this in plain js + blue bird? Thanks for your time.

Community
  • 1
  • 1
  • 1
    Node is plain js. (Also, your link has no reference of node) – Amit May 29 '15 at 12:46
  • Sorry but I don't use node.js - are you telling me that .method() and process.nextTick() are available as js functions outside of node.js? – user3306881 May 29 '15 at 12:49
  • I don't know what `promise.method()` is, or where you saw this. (also not in the link) – Amit May 29 '15 at 13:03
  • Thanks - as I don't use node.js I don't know either, but it is used in Bergi's answer to this: http://stackoverflow.com/questions/24660096/correct-way-to-write-loops-for-promise?lq=1 - this is the most useful answer I have seen yet - but still in node.js ... – user3306881 May 29 '15 at 13:08
  • @user3306881: No, I did **not** use node js in my answer. My post only contains `db.getUser` and `logger.log` and the `console` object in the examples, not in the `promiseWhile` solution. Only the OP did use `process.nextTick` in his *question* - for no apparent reason. – Bergi May 29 '15 at 14:55
  • And yes, [`Promise.method`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisemethodfunction-fn---function) is part of the Bluebird library, it is available everywhere with Bluebird and is not part of node js. – Bergi May 29 '15 at 14:57
  • Thanks - I don't use logger.log and .method hung in just plain js + bluebird - the only solution I have so far that works in bare js + bluebird is the one marked as the answer to this question. But thanks for the clarifications. – user3306881 May 29 '15 at 15:08

1 Answers1

0

Well, once something is a promise returning function - you don't really care about the environment the library takes care of it for you:

Promise.delay(1000); // an example of an asynchronous function

See this question on converting functions to promise returning ones.

Now, once you have that sort of function a loop becomes pretty trivial:

function whileLoop(condition, fn){
    return Promise.try(function loop(val){
          return Promise.resolve(condition()).then(function(res){
              if(!res) return val; // done
              return fn().then(loop); // keep on looping
          });
    });
}

Which would let you do something like:

var i = 0; 
whileLoop(function(){
   return i < 10; // can also return a promise for async here
}, function body(){
    console.log("In loop body");
    i++;
    return Promise.delay(1000);
}).then(function(){
    console.log("All done!");
});

To demonstrate this works in a browser - here's a JSFiddle

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504