javascript - While loop using bluebird promises -


i trying implement while loop using promises.

the method outlined here seems work. http://blog.victorquinn.com/javascript-promise-while-loop uses function this

var promise = require('bluebird');  var promisewhile = function(condition, action) {     var resolver = promise.defer();      var loop = function() {         if (!condition()) return resolver.resolve();         return promise.cast(action())             .then(loop)             .catch(resolver.reject);     };      process.nexttick(loop);      return resolver.promise; }; 

this seems use anti-patterns , deprecated methods cast , defer.

does know better or more modern way accomplish this?

thanks

cast can translated resolve. defer should indeed not used.

you'd create loop chaining , nesting then invocations onto initial promise.resolve(undefined).

function promisewhile(predicate, action, value) {     return promise.resolve(value).then(predicate).then(function(condition) {         if (condition)             return promisewhile(predicate, action, action());     }); } 

here, both predicate , action may return promises. similar implementations have @ correct way write loops promise. closer original function be

function promisewhile(predicate, action) {     function loop() {         if (!predicate()) return;         return promise.resolve(action()).then(loop);     }     return promise.resolve().then(loop); } 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -