Continuation synchronous and asynchronous
suggest changeCallbacks can be used to provide code to be executed after a method has completed:
/**
* @arg {Function} then continuation callback
*/
function doSomething(then) {
console.log('Doing something');
then();
}
// Do something, then execute callback to log 'done'
doSomething(function () {
console.log('Done');
});
console.log('Doing something else');
// Outputs:
// "Doing something"
// "Done"
// "Doing something else"
The doSomething() method above executes synchronously with the callback - execution blocks until doSomething() returns, ensuring that the callback is executed before the interpreter moves on.
Callbacks can also be used to execute code asynchronously:
function doSomethingAsync(then) {
setTimeout(then, 1000);
console.log('Doing something asynchronously');
}
doSomethingAsync(function() {
console.log('Done');
});
console.log('Doing something else');
// Outputs:
// "Doing something asynchronously"
// "Doing something else"
// "Done"
The then callbacks are continuations of doSomething() and doSomethingAsync(). Scheduling one with setTimeout is not a tail call: the timeout call returns immediately, and then runs later on a new turn. A tail call returns the result of a call in tail position. ES2015 specifies proper tail calls, but most engines never implemented that optimization.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents