Syntax
The two new keywords, async
/await
, are often found together, but not always. Let's look at the syntax for each of them individually.
async
The async
keyword modifies a function. If a function declaration or function expression is used, it is placed before the function
keyword. If an arrow function is used, the async
keyword is placed before the argument list. Adding the async
keyword to a function will cause the function to return a promise.
For example:
function addAsync(num1: number, num2: number) { return num1 + num2; }
Just adding the async
keyword to this simple function will make this function return a promise, which is now awaitable and thenable. Since there's nothing asynchronous in the function, the promise will resolve immediately.
The arrow function version of this could be written as follows:
const addAsync = async (num1: number, num2: number) => num1 + num2;
Exercise 13.02: The async Keyword
This exercise illustrates...