Callback execution

Let's go through an example of using callbacks in asynchronous code in the TypeScript playground. Let's enter the following code:

let firstName: string;
setTimeout(() => {
firstName = "Fred";
console.log("firstName in callback", firstName);
}, 1000);
console.log("firstName after setTimeout", firstName);

The code calls the JavaScript setTimeout function, which is asynchronous. It takes in a callback as the first parameter and the number of milliseconds the execution should wait until the callback is executed as the second parameter.

We use an arrow function as the callback function, where we set the firstName variable to "Fred" and output this to the console. We also log firstName in the console immediately after the call to setTimeout.

So, which console.log statement will get executed first? If we run the code and look at the console, we'll see that the last line is executed first:

The key point is that after setTimeout is called, execution carries on to the next line of code. Execution doesn't wait for the callback to be called. This can make code that includes callbacks harder to read than synchronous code, particularly when we have callbacks nested within callbacks. This is referred to as callback hell by many developers!

So, how do we handle errors in asynchronous callback code? We'll find out in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.143.239