Execute Program

JavaScript Concurrency: Async/await Gotchas

Welcome to the Async/await Gotchas lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Async/await doesn't have a lot of gotchas, but there are a couple to point out. First, we can't use await outside of an async function. If we do, it will cause an error. Fortunately, this is a syntax error, so we'll see it immediately and our JavaScript code won't even begin running.

  • (You can type error when a code example will cause an error.)

  • >
    function five() {
    await Promise.resolve(5);
    }
    Result:
    SyntaxError: on line 2: Unexpected reserved word 'await'.Pass Icon
  • An async function without any awaits is allowed. However, doing that still adds complexity. All async functions return promises, even if they don't await. So, the function's return value will automatically be wrapped in a fulfilled promise.

  • >
    async function double(n) {
    return n * 2;
    }
    double(5);
    Asynchronous Icon Async Result:
    {fulfilled: 10}Pass Icon
  • It's possible to await non-promise values, like await 5. When we do that, we get the value back immediately without any waiting.

  • >
    async function double(n) {
    return (await n) * 2;
    }
    double(5);
    Asynchronous Icon Async Result:
    {fulfilled: 10}Pass Icon
  • Sometimes that's a mistake, but it's also possible to do this intentionally. Our double function above will work if we pass it a number, but it will also work if we pass it a promise fulfilled with a number.

  • >
    async function double(n) {
    return (await n) * 2;
    }
    double(Promise.resolve(6));
    Asynchronous Icon Async Result:
    {fulfilled: 12}Pass Icon
  • Those are our only notes on potential sharp edges or less-obvious parts of async/await. These aren't design mistakes in JavaScript; they're just aspects of the language that may not be obvious at first. If you understand promises well, using async/await should be a smooth experience. And if you get stuck, you can manually translate the async/await code into regular promise code to understand what's happening.