Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await outside of async function doesn't throw error in console

MDN says:

Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.

But that's not true.

Try this code in DevTools console, no errors, just result:

async function a(val) { return val; }
await a(10) // await is not inside async function
10

What's wrong with the code or docs?

like image 666
Green Avatar asked Dec 23 '18 17:12

Green


1 Answers

Nothing is wrong.

You've found a special feature of the DevTools console! It is there to make it as easy as possible to experiment with async-await code in a live environment. You can imagine that any code you enter in the console is wrapped in an async function automatically. In fact, as another answer pointed out, this is exactly what happens.

It's important to note that even though this works in the console, it is not a feature of JavaScript.

So, all of your observations are correct and expected! The MDN docs are accurate, because if you try to load a script on a page that uses await outside of an async function, it will error. On the other hand the DevTools console is designed to make this work (exclusively for developer ergonomics), so your code runs without any errors in the console.

This isn't the only trick the DevTools console has up its sleeve. In general if you really want to test how some code runs on a page, it's best to actually run the script on the page, not in the console.

like image 98
Caleb Miller Avatar answered Oct 14 '22 14:10

Caleb Miller