JavaScript Concurrency: Async/await in Arrow Functions
Welcome to the Async/await in Arrow Functions lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
So far we've only seen async/await in regular JavaScript functions, but it works in arrow functions too. The
asynccomes before the parameter list, andawaitcan be used in the body as normal.>
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));sleep(500).then(() => 'it worked');Async Result:
{fulfilled: 'it worked'}Here's that same function with async/await.
>
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const delayed1 = async () => {await sleep(500);return 'it worked';};delayed1();Async Result:
{fulfilled: 'it worked'}Fortunately, there's nothing else that's special about asynchronous arrow functions. They work just like regular functions!
Here's a code problem:
We rewrote
sleepbelow as an arrow function usingawait. It's not an async function, so theawaitcauses an error. Change the function to make it async.const sleep = async (ms) => {await new Promise(resolve => setTimeout(resolve, ms));};const startTime = new Date().getTime();sleep(500).then(() => {const now = new Date().getTime();const elapsed = now - startTime;return elapsed >= 100;});Async Result:
- Goal:
{fulfilled: true}- Yours:
{fulfilled: true}