Reputation: 13
Newbe in JavaScript, I've 4 function say :
function funct1(){
//dosomething();
}
function funct2(){
//dosomething();
}
function funct3(){
//dosomething();
}
function funct4(){
//dosomething();
}
I want to exécute funct1 THEN funct2 and funct3. But I do want funct4 to be executed ONLY after funct2 AND funct3 have finished ! How can'I achieve this, I guess there is a better way to do this ??
I've try this but not very sure of what is running
function foo(callback){
funct1;
funct2;
funct3;
callback();
}
function bar(){
foo(funct4);
}
Upvotes: 0
Views: 85
Reputation: 25310
If one (or all) of your functions is async, given that you've tagged your question with jQuery, you can just use promises.
function funct1(){
var dfd = $.Deferred();
//Inside some async function, eventually:
dfd.resolve();
//More code
return dfd.promise();
}
You can then daisy chain your functions together as shown in the answer by Victor.
If you need to wait for multiple promises to finish (and run multiple in parallel), you can use
$.when(funct1, funct2).done(function (arg1, arg2) {
});
Upvotes: 0
Reputation: 628
You can do that by following:
$.when(funct1).then(funct2).then(funct3).then(funct4)
jQuery has own realization of promises, please take a look at documentation or nice tutorials like that http://tutorials.jenkov.com/jquery/deferred-objects.html
Upvotes: 2