Created Thursday 24 June 2021
Recent versions of JavaScript include support for async functions and the await keyword. Below, I enumerate a few edge cases of async
/await
in Google Chrome that produce obscure errors, and their solutions. I'm using Chrome 91.0.4472.114. I don't know if these are known bugs, but they were confusing to me. I'm grateful to anyone with the time and interest to officially catalog and/or fix them.
This one can come up when you use await in a function where it's not allowed. The following code doesn't work because neither the outer function nor inner arrow function were decorated with the async
keyword.
function foo(xs) { return xs.map(x => await x); }
VM856:1 Uncaught SyntaxError: missing ) after argument list
You can still get the error even if the enclosing outer function is async:
async function foo(xs) { return xs.map(x => await x); }
VM867:1 Uncaught SyntaxError: missing ) after argument list
I can imagine how the compiler could make the inner async work, since the inner arrow function doesn't escape the outer function. I haven't looked at the specification, but I assume it's not supposed to work. It's OK with me that it doesn't work, because if it did, the rules about when async
works would become more complicated. The error message could be better, though.
This one must be a consequence of the way template literals and the await
keyword interact:
function foo(x) { return `${await x}`; }
VM960:1 Uncaught SyntaxError: Missing } in template expression
Contrary to the error message, the problem is unrelated to the template expression syntax. The problem is that the foo
function needs to be async:
async function foo(x) { return `${await x}`; }