There are countless similar threads to this but no canonical ones which seemed to answer my question. There are also many which seem to involve really complicated solutions to what seems should have a simple solution.
Anyway, my basic question is how do you get this to run in order:
console.log('step 1');
$.getJSON('foo.json', function(data) {
console.log('step 2');
});
console.log('step 3');
This results in a console output of:
step 1
step 3
step 2
It seems reasonable that something like this might be available which would stall the function until the file has been loaded but it doesn't work.
$.getJSON('foo.json', function(data) {
console.log('step 2');
}).done();
Other threads suggest you can create $.Deferred()
objects which can chain calls like then().then()
before finalizing them somehow but this doesn't help because I actually have functions of this fashions:
function first() {
$.getJSON('foo.json', function(data) {
console.log('step 1');
});
}
function second() {
$.getJSON('foo.json', function(data) {
console.log('step 2');
});
}
// Even if I defer them to wait until the next function finishes,
// the `getJSON` calls won't have finished and I'm back where I started.
function call_them() {
first();
second();
console.log('step 3');
}
Other places it was suggested that I could try using $.when()
which seemed like a big hassle even if it would work but it didn't when I tried. I tried something like this:
function do_first() {
$.when(first())
.done(function() { console.log('first is finished'); });
}
function first() {
return $.getJSON('foo.json', function(data) {
console.log('step 1');
});
}
function do_second() {
$.when(second())
.done(function() { console.log('second is finished'); });
}
function second() {
$.getJSON('foo.json', function(data) {
console.log('step 2');
});
}
function call_them() {
do_first();
do_second();
console.log('step 3');
}
Anyway, this seems like it should be really easy but I have no idea how you're supposed to make this work. Also, it works perfectly when async
is disabled but that is untenable for the website which utilizes this.