Reputation: 347
I have some javascript code that uses anonymous functions. I suspect, but am not sure, that the functions are called independent of their order in the code.
app_service.callbackOfSomeKind( function (result) {
console.log("result: 1" );
} );
app_service.AnotherCallback( function (result) {
console.log("result: 2" );
} );
how do I make sure that result 2 prints after result 1??? How do I make sure that AnotherCallback isn't even seen by JS till the code in callbackOfSomeKind is run? I was thinking of doing this:
app_service.callbackOfSomeKind( function (result) {
console.log("result: 1" );
app_service.AnotherCallback( function (result) {
console.log("result: 2" );
} );
} );
but is there a better way?
Upvotes: 0
Views: 54
Reputation: 16726
promises are great and i recommend looking into them, but there's a way to simplify the nesting wihout major refactoring by using named callbacks instead of anons:
function someCallback(result) {
console.log("result: 1" );
app_service.AnotherCallback( someOtherCallback );
}
function someOtherCallback(result) {
console.log("result: 2" );
}
app_service.callbackOfSomeKind( someCallback );
in this manner, you can still get the execution order you need, but without nested anon callbacks that are hard to maintain and debug. i guess it's sort of a compromise between your first and second examples, but with reduced complexity and closure costs.
Upvotes: 2