简体   繁体   中英

Plain JavaScript + bluebird promises asynchronous for/while loop WITHOUT USING NODE.JS

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 (eg promise.method() or process.nextTick() ; eg such as: While loop using bluebird promises ). Is there any way to do this in plain js + blue bird? Thanks for your time.

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

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