.then()
handlers accept function references as arguments, not promises. Your code was executing your ajax calls immediately and then passing the returned promise to the .then()
handler which is not valid.
If you want the Ajax calls to be executed later and in sequence, then you need to put them in a function like this so you can pass that function reference to .then()
. In that way, the promise infrastructure can call your function some time in the future:
var chain = Q();
for (var i = 0; i < x.length; i++) {
chain = chain.then(function(priorResults) {
return $.ajax({
type: "POST",
url: data_url,
data: pdata
});
});
}
return chain;
You pass a function reference to a .then()
handler so the promise infrastructure can execute that function at some later time.
As you had it, the $.ajax()
calls were all executed immediately and only the promises where chained.
If you are attempting to use the i
variable inside the .then()
handler, that will not work properly because the for
loop will have finished and i
will have its terminal value when the .then()
handler is called. The usual solution is either to use let
in ES6 for the for
loop variable, iterate with something like .forEach()
or to make sure the for
loop contains a function/closure that can uniquely capture each separate value of the i
variable. More details could be provided if you showed your actual code.
P.S. I presume there is some missing code in your question because you probably don't want to execute the exact same Ajax call each time.
If you are iterating an array, then a common design pattern for iterating an array serially using promises is with .reduce()
like this:
array.reduce(function(p, item) {
return p.then(function(priorResult) {
return $.ajax(...);
});
}, Q()).then(function(result) {
// everything done here, final result
});