Asynchronous functions are functions created with the async keyword. They let you use an await keyword to wait for promises to resolve. This await lets you write asynchronous code as if they were synchronous.
Declaring asynchronous functions
You declare asynchronous functions with an async keyword. The async keyword must be placed before the function keyword.
// Function declarationasync function functionName(arguments) { // Do something asynchronous}You can also create asynchronous functions with the arrow function syntax. In this case, you write async before the arguments.
const functionName = async arguments => { // Do something asynchronous}Using asynchronous functions
You can call asynchronous functions like normal functions. You write the name of the function, followed by parenthesis.
// Calling an async functionanAsyncFunction()Asynchronous functions always return a promise
It doesnโt matter what you return. The returned value will always be a promise.
async function getOne() { return 1}
const promise = getOne()console.log(promise) // Promise
This means you can treat asynchronous functions like promises. If you return a value from an asynchronous function, you can use that value in the next then call.
async function asyncSum(num1, num2) { return num1 + num2}asyncSum(5, 10).then(result => console.log(result)) // 15The await keyword
The await keyword is where the magic happens. It waits for a promise to resolve before doing anything else.
Letโs say we send a Fetch request for a list of my repositories. This is how we write the Fetch request if we use promises.
fetch('https://api.github.com/users/zellwk/repos') .then(response => response.json()) .then(repos => console.log(repos))We can perform the same Fetch request with asynchronous functions. To do so, we first create an asynchronous function.
We can place the promise we wrote in the asynchronous function. Itโll work as before.
async function fetchRepo(link) { return fetch(link) .then(response => response.json()) .then(repos => console.log(repos))}
fetchRepo('https://api.github.com/users/zellwk/repos')We know Fetch returns a promise. We can use await to wait for Fetchโs promise to resolve in an asynchronous function. We can declare a variable to hold this resolved value.
async function fetchRepo(link) { const response = await fetch(link) console.log(response)}
fetchRepo('https://api.github.com/users/zellwk/repos')Try logging response into the console. Youโll see that itโs the same response that is returned from a Fetch request.
We need to call response.json to get the repos. Since response.json returns a promise, we can also use await to wait for this promise to resolve.
async function fetchRepo(link) { const response = await fetch(link) const repos = await response.json() console.log(repos)}
fetchRepo('https://api.github.com/users/zellwk/repos')If you log repos, youโll see a list of 30 repositories.
Return await
Thereโs no need to await before returning a promise. You can return the promise directly.
If you return await something, you resolve the original promise first. Then, you create a new promise from the resolved value. So return await effectively does nothing. No need for the extra step. We can return the promise directly.
async function fetchRepo(link) { const response = await fetch(link) // No need to do this return await response.json()}async function fetchRepo(link) { const response = await fetch(link) // Do this instead return response.json()}Handling errors
await waits for the promise to resolve. It only waits for the then call. This means wonโt handle errors in the asynchronous function we wrote.
Letโs see this in action. Say we await for a promise that always throws an error, errorPromise. Youโll see an โuncaughtโ error in your console.
function errorPromise() { return new Promise((resolve, reject) => { reject(Error('Something went wrong!')) })}
async function asyncFunction() { const res = await errorPromise()}
asyncFunction()
We get this โuncaughtโ error message because we didnโt catch the error in our code. The console caught it for us, and it tells us that we need to catch the error.
We can use a try/catch block to handle errors in an asynchronous function. A try/catch block looks like this:
try { // Try something that may cause an error} catch (error) { // Do something if an error occurs}Promises that resolve will always go into the try block. Promises that reject will always go into the catch block.
async function asyncFunction() { try { const res = errorPromise() // Code continues here if successful } catch (error) { // Code goes here if something goes wrong console.log(error) }}
The try block works like this: it executes code from top to bottom, left to right (like normal). When it encounters an error, it skips the rest of the code and goes straight to the catch block.
async function asyncFunction() { try { const res = await errorPromise() console.log('JavaScript will never read this line of code!') } catch (error) { console.log(error) }}The promise catcher
Error handling with try/catch works, but it makes the code harder to digest. We donโt want to write try/catch blocks for every asynchronous function we write. It would be horrible!
For this example, imagine that getOne, getTwo and getThree are promises).
async function asyncFunction() { try { const one = await getOne(false) } catch (error) { console.log(error) }
try { const two = await getTwo(false) } catch (error) { console.log(error) }
try { const three = await getThree(false) } catch (error) { console.log(error) }}Thereโs a way to make error catching easier.
We know asynchronous functions return promises. This means we can catch errors with a catch call after calling an asynchronous function. With the catch call in place, we no longer need to write try/catch blocks.
async function asyncFunction() { const one = await getOne(false) const two = await getTwo(false) const three = await getThree(false)}
asyncFunction().catch(e => console.log(e)) // Error: Something went wrong!Exercise
- Use an asynchronous function to fetch a list of your repositories
- Handle async errors with the try/catch block
- Handle async errors with a Promise
catchcall
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson