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
awaitoutside of anasyncfunction. 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
errorwhen a code example will cause an error.)>
function five() {await Promise.resolve(5);}Result:
SyntaxError: on line 2: Unexpected reserved word 'await'.
An async function without any
awaits is allowed. However, doing that still adds complexity. All async functions return promises, even if they don'tawait. So, the function's return value will automatically be wrapped in a fulfilled promise.>
async function double(n) {return n * 2;}double(5);Async Result:
{fulfilled: 10}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);Async Result:
{fulfilled: 10}Sometimes that's a mistake, but it's also possible to do this intentionally. Our
doublefunction 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));Async Result:
{fulfilled: 12}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.