Instructor: The make a function async, all you need to do is prefix it with the async keyword. Async can be used with simple functions, error functions, and class methods. Let's discuss the nature of async functions in isolation by focusing in on a simple function.
If we return a value from that function, of course, the promise will resolve to that value. TypeScript is smart enough to infer the return type for async functions to be the promise of the returned values. With the return value of async functions out of the way, let's focus in on the body of an async function.
We set up Node.js to ignore any unhandled promise rejections to have a clean console. Next, we set up a few promises to use in our async function. We create a variable that is not a promise. We create a promise that will resolve. Finally, we also create a promise that will reject.
Async functions get access to the await operator in their function bodies. The await operator can be applied to any variable. If the variable is not a promise, the value returned for the await operator is same as the variable.
If the variable is a promise, execution in the function body pauses until the fate of the promise is determined. If the promise resolves the value of the await operator, it's the resolve value of the promise. If the variable is a promise that gets rejected, the await operator throws an error in the body of the async function.
This means no subsequent statements execute unless there is a catch construct, similar to try/catch in synchronous code. Let's go ahead and call this function to verify that it works as explained. The not a promise variable just resolves to itself. The promise that will resolve returns its final resolved value, and the promise that gets rejected interacts with the try/catch as expected.
If a promise takes some time to settle in its fate, execution at the await operator pauses until the fate is determined. Here, we are going to wait five seconds before determining the fate of this local promise. If we go ahead and run this code, you can see that the execution pauses for five seconds, and then the next line, done waiting, is executed.
Essentially, async await allows you write asynchronous code based on promises in a manner that allows you to reuse your synchronous code writing skills.