Async/Await
Learn the modern way to write asynchronous JavaScript. Async/await is quickly becoming the industry standard and it's an important tool to learn.
We'll cover the following...
async
/await
We’ve covered callbacks and promises. Now we get to the latest async feature that will change how we write asynchronous functions in JS.
This is a feature that truly makes asynchronous code much easier to write. Let’s dive right in.
Introduction
An asynchronous function is created using by writing the async
keyword before a function. Here’s what it looks like for a standard function.
async function fn() {...}
const fn = async function() {...}
Here’s what it looks like for an arrow function.
const fn = async () => {...}
Inside an asynchronous function, we can use the await
keyword to make the function pause and wait for some operation to complete.
Here, I’ve written a function wait
that takes in a number and returns a string after that number of seconds. The function fn
calls wait
. When wait
completes and resolves, fn
continues executing.
- Note that these asynchronous functions won’t work very well here in Educative’s code blocks. I recommend you use another JS environment such as https://repl.it/site/languages/javascript.
Example
function wait(secondsToWait) {return new Promise(resolve => {setTimeout(() => resolve(`Resolved after ${secondsToWait} seconds`),secondsToWait * 1000);});}async function fn() {console.log('Beginning fn');const result = await wait(2);console.log(result);console.log('Ending fn');}fn();
What’s Going On
Let’s walk through the series of steps here.
We start by invoking our async function fn
on line 19. Immediately, "Beginning fn"
is logged to the console.
The ...