Callbacks
Let's start by examining callbacks, which is the standard mechanism for registering a function to execute after an asynchronous event has occurred. Consider the following example:
function delayedResponseWithCallback(callback: () => void) {
function executeAfterTimeout() {
console.log(`5. executeAfterTimeout()`);
callback();
}
console.log(`2. calling setTimeout`)
setTimeout(executeAfterTimeout, 1000);
console.log(`3. after calling setTimeout`)
}
Here, we have a function named delayedResponseWithCallback
that has a single parameter named callback
, which is a function with no arguments that returns void. Within this function, we define another function named executeAfterTimeout
, which will log a message to the console, and then execute the callback function that was passed in as the parameter named callback
. Note that each console log in this snippet starts with a number, which shows the order of execution of the statements...