using jQuery 3.2.1 I'm chaining calls to $.ajax like this:
function get(i) {
return $.ajax(...)
.done(function() { console.log('get done: ' + i) })
.fail(function() { console.log('get failed: ' + i) })
}
var p = Promise.resolve();
for (var i = 0; i < len; i++) {
p = p.then(get(i));
}
p.done(function() { console.log('Finished') });
and I would expect that the ajax call for i=1 would not execute until the call for i=0 had resolved. similarly, the final done() should wait for all the calls to be performed in order
in reality I'm seeing 'Finished' before I see anything else and the 'get done' are coming back in random order (the first one finished comes back first is my guess).
I'm used to Bluebird where this would work. what am I doing wrong?
* Addendum I *
to add to the above, I'm loading javascript files that have dependencies and thus need to be loaded in order. therefore, the first must complete before the second fetch is initiated, otherwise dependencies will fail
There are two issues:
The get function is executed immediately, while the then
method should get a reference to that function for later execution by the Promise implementation. So replace:
p = p.then(get(i));
with:
p = p.then(get.bind(null,i));
JavaScript's native promises do not expose the done
method, so replace:
p.done(function() { console.log('Finished') });
with:
p.then(function() { console.log('Finished') });
You should probably also add a catch
call to the final promise.
Corrected version:
function get(i) {
return $.ajax('https://jsonplaceholder.typicode.com/posts/'+(i+1))
.done(function() { console.log('get done: ' + i) })
.fail(function(err) { console.log('get failed: ' + i) })
}
var len = 4;
var p = Promise.resolve();
for (var i = 0; i < len; i++) {
p = p.then(get.bind(null,i));
}
p.then(function() { console.log('Finished') })
.catch(function () { console.log('Error occurred') });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>