In this section, we will learn what the async is and how to use it in JavaScript.
Note: we’re assuming you’re already familiar with the JavaScript Promise.
JavaScript async Function
The async functions are built on top of Promises and they provide syntax for writing asynchronous code using the same familiar flow control structure we use when writing synchronous code (Like `for` loops, `if` statements, `try/catch/finally`, calling functions and waiting for their results, etc.)
JavaScript async Function Syntax
An async function is declared by adding the `async` keyword in front of a function. This keyword can be used on function declaration, function expression, arrow function, and methods.
Example:
async function foo() {} let bar = async function() {}; let baz = async () => {}; class Qux { async qux() {} }
Note: the class and methods are covered in later sections.
JavaScript await Statement
You should know that just by adding the `async` keyword to a function, that function won’t act asynchronously! It’s mainly the `await` keyword that turns an operation in the target `async` function into asynchronous.
The `await` keyword is explained in the next section, but before getting into that section, there are a couple of notes that we should know about an `async function`.
An async function always returns a Promise object. Even when we don’t explicitly return a value from a function, it will return a Promise object that is settled into `resolve` with the value `undefined`.
This means we can create handlers for an `async function` via either `then or catch` methods.
Example: creating async function in JavaScript
async function func(){ } console.log(func()); const prom= func(); prom.then(resolve=>{ console.log("In the resolve handler"); console.log(resolve); })
Output:
Promise {<fulfilled>: undefined} In the resolve handler undefined
As you can see, every time we call the `func()` it will return a resolved Promise object.
JavaScript async function and the return statement
We can use the `return` statement in an `async function` as well, however the function still returns a Promise object that is settled into resolve but it will use the value of the `return` keyword as the value of the resolved Promise that was returned from the function.
Example: creating async function with return statement
async function func(){ return [1,2,3,4] } console.log(func()); const prom= func(); prom.then(resolve=>{ console.log("In the resolve handler"); console.log(resolve); })
Output:
Promise {<fulfilled>: Array(4)} In the resolve handler (4) [1, 2, 3, 4]
As you can see, the returned Promise object from the `func () ` function has the array-value of the `return` statement as its resolved value. And we can simply access this array in the handler of the resolved Promise.
JavaScript async Function and Errors
If anything went wrong in an `async function` and an error is thrown, there are two cases that can happen here:
1- We can handle that error via the `try catch` statement in the function itself and finally return a resolved Promise.
Example: handling errors in an async function
async function func(){ try{ throw new Error("Simple Error"); }catch(error){ console.log("In the body of the catch block"); console.log(error.message); } } const prom= func(); prom.then(resolve=>{ console.log("In the resolve handler"); console.log(resolve); })
Output:
In the body of the catch block Simple Error In the resolve handler undefined
2- If the error is not handled correctly in the function, the returned value from the `async function` will be a Rejected Promise object. So we can use the `catch` method in the handlers to handle such error. (The created error object will be used as the reason for the rejection).
Example: handling errors in async functions using Promise catch blocks
async function func(){ throw new Error("Simple Error"); } const prom= func(); prom.then(resolve=>{ console.log("In the resolve handler"); console.log(resolve); }).catch(reject=>{ console.log("In the reject handler"); console.log(reject); })
Output:
In the reject handler Error: Simple Error
In the body of the `func()` we didn’t handle the error via the `try/catch` block and so as a result, the function returned a Promise object that is settled into the `rejection`. So the rejection handler of this Promise will be executed.
JavaScript async function with Promise object
Besides the auto-created Promise in the `async functions` we can also manually create a Promise object and return that as the return value of the function.
Example: creating promise object in an async function
async function func(){ return new Promise ((resolve,reject)=>{ setTimeout(()=>{ resolve("Done after 3 seconds"); },3000) }) } func().then(resolve=>{ console.log("In the resolve handler"); console.log(resolve); }).catch(reject=>{ console.log("In the reject handler"); console.log(reject); })
Output:
In the resolve handler Done after 3 seconds
Alright, that’s it for this section. In the next section, we will explain how the `await` keyword is used in the `async` functions.