Technically the pattern you're asking for is:
function myFunctionNeedsACallback(param1, callback) {
//do stuff with param1
if(typeof callback === "function"){
callback.call(yourThisParam, anyOtherParams);
}
}
While this is a useful pattern... overuse will lead to ugly, untestable, and unmaintainable code. Use with discretion.
Your example would work just fine:
myFunctionNeedsACallback(param, function() { alert('2'); });
//will alert 2 after running the rest of the contents of the function
EDIT
To address thomas's situation:
function ajaxCall1(){
return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/);
}
function ajaxCall2(){
return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/);
}
function ajaxCall3(){
return $.ajax(/*your parameters NO SUCCESS CALLBACK NEEDED*/);
}
$.when(ajaxCall1(), ajaxCall2(), ajaxCall3()).then(function(results1, results2, results3) {
//do stuff with all 3 results without "nesting" things
});