简体   繁体   中英

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?

MDN docs is right and it explains how it works in JavaScript.

This is just a feature added by the DevTools for making you easier to test async/await code. And it is not a JavaScript feature.

It looks like it has been supported since 11/08/2017 in DevTools:

https://chromium.googlesource.com/chromium/src.git/+/e8111c396fef38da6654093433b4be93bed01dce

If you spy the

ConsoleModel.js

at line 129, they have the function for evaluating expressions marked as async:

async evaluateCommandInConsole

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM