A chain of nested promises in a loop

I am new to promises and stuck in the next exercise.

I have an array of values, and I want to make an asynchronous call for each of them. In the callback, I want to make another call based on the result of the first call.

Basically, my disappointment is this: The execution order should be "1x2x3x", but the order is "123xxx"

In other words, the loop is already going to the next iteration when the sub / nested promise of the first promise is not yet filled.

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) }); }); return deferred.promise; } var result = do(values[0]); values.forEach( function(f) { result = result.then(do(f)); } 

This may be a simple solution, but I am stuck on it.

+7
javascript promise loops nested order
source share
1 answer

You do not need to postpone that you have a pending anti-pattern from the promises chain.

In addition, you must return the promise from the .then handler if you want it to wait for its permission.

You can simply use the for loop:

 function do(val) { var q = Q(); for(var i = 0; i < val; i++){ q = q.then(asyncCall.bind(null,i)) .then(console.log.bind(console)) .then(console.log.bind(console,"x")); } return q; // in case you want to chain } 

fiddle

Note. The binding simply captures the value to call the function. In this case, since the first parameter ( this value) is null, it acts like function(fn,arg){ return function(arg){ return fn(arg); }} function(fn,arg){ return function(arg){ return fn(arg); }} , that is, it transfers the function call to a "partial application" - see the MDN documents for more information.

+5
source share

All Articles