Your callback solution would work perfectly, except you're calling the callback in the wrong place:
// function 1
function function_1(callback) {
// replicating something that takes a while
// alert("1");
setTimeout(function() {
$("p").append("This should happen first.");
callback(); // <=== Here, when the thing is done
}, 300);
// callback(); // <=== Not here, when you've only started it and it's not done yet
}
If you want to use promises instead of an explicit callback, you can do that too. Promises are not part of the JavaScript language; JavaScript functions do not make promises available by themselves, which is why function_1.done
didn't work. You create the promise (with jQuery, in the form of a Deferred
object) and return it from the function, then use it with the other function:
// function 1
function function_1() {
var d = new $.Deferred();
setTimeout(function() {
$("p").append("This should happen first.");
d.resolve(); // <=== Resolve the deferred, now that the action is complete
}, 300);
return d.promise(); // <=== Return the Promise for the Deferred
}
//function 2
// only do this when function one has finished
function function_2() {
alert("This should happen second.");
};
// the call
function_1().done(function_2);