node.js - Nodejs / Q : Chaining promises sequentially -


i want simple, don't understand little thing ...

var q = require('q');  var funcs = ["first", "second", "third", "fourth"];  function main(){  // don't know how chain sequentially here ...     var result = q();      funcs.foreach(function (f) {         result = treat(f).then(f);     });  }  function treat(t){      var deferred = q.defer();      settimeout(function(){         deferred.resolve("treated "+ t);      },2000);      return deferred.promise; }  main(); 

i each element of funcs array "treated" sequentially, output :

treated first //2 seconds later treated second //2 seconds later treated third //2 seconds later treated fourth 

i cannot achieve :( should simple , don't catch :(

judging example, assume saw sequences part of q readme, failed understand it.

original example used "waterfall" model, when output of each function passed input next one:

var funcs = [foo, bar, baz, qux];  var result = q(initialval); funcs.foreach(function (f) {     result = result.then(f); }); return result; 

but want execute our functions in sequence, bind each function variables:

var args = ["first", "second", "third", "fourth"];  var result = q(); args.foreach(function (t) {     result = result.then(treat.bind(null, t)); }); return result; 

in example treat function called 4 times sequentially, , result promise resolved value of latest treat call (results of previous calls ignored).

the trick .then method accepts handler called after current promise resolved , returns new promise. so, should pass .then function should called on next step of execution chain. treat.bind(null, t) binds treat function attribute t. in other words, returns new function, invoke treat, passing t first argument.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -