javascript - chaining nested promises in a loop -
i kind of new promises , stuck on next exercise.
i have array of values , want execute async phone call on each one. in callback, want execute phone call on outcome of first call.
basically, frustration in following: order of execution should '1x2x3x' order '123xxx'
in other words, loop going next iteration when sub/nested promise of first promise not fullfilled yet..
var values = ["1", "2", "3"]; function do(val) { var deferred = q.defer(); asynccall(val) .then( function( response ) { console.log(val); asynccall(response) .then( function ( response ) { console.log('x'); deferred.resolve(true) }); }); homecoming deferred.promise; } var result = do(values[0]); values.foreach( function(f) { result = result.then(do(f)); }
there easy solution i'm stuck on it.
you don't need deferred, that's deferred anti pattern have there since promises chain.
also, have homecoming promise .then
handler if want wait resolve.
you can utilize loop:
function do(val) { var q = q(); for(var = 0; < val; i++){ q = q.then(asynccall.bind(null,i)) .then(console.log.bind(console)) .then(console.log.bind(console,"x")); } homecoming q; // in case want chain }
fiddle.
note: bind fixates value function call. in case since first param (the this
value) null acts function(fn,arg){ homecoming function(arg){ homecoming fn(arg); }}
is, translates function phone call "partial application" - more info see mdn docs.
javascript loops nested order promise
No comments:
Post a Comment