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


there seem many answers questions on how use bluebird promises call asynchronous functions / while loop, far can see, require node.js work (e.g. promise.method() or process.nexttick() ; e.g. such as: while loop using bluebird promises ). there way in plain js + blue bird? time.

well, once promise returning function - don't care environment library takes care of you:

promise.delay(1000); // example of asynchronous function 

see this question on converting functions promise returning ones.

now, once have sort of function 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 let like:

var = 0;  whileloop(function(){    return < 10; // can return promise async here }, function body(){     console.log("in loop body");     i++;     return promise.delay(1000); }).then(function(){     console.log("all done!"); }); 

to demonstrate works in browser - here's jsfiddle


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -