Execute Program

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 async comes before the parameter list, and await can be used in the body as normal.

  • >
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
    sleep(500).then(() => 'it worked');
    Asynchronous Icon Async Result:
    {fulfilled: 'it worked'}Pass Icon
  • 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();
    Asynchronous Icon Async Result:
    {fulfilled: 'it worked'}Pass Icon
  • 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 sleep below as an arrow function using await. It's not an async function, so the await causes 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;
    });
    Asynchronous Icon Async Result:
    Goal:
    {fulfilled: true}
    Yours:
    {fulfilled: true}Pass Icon