简体   繁体   English

在异步函数之外等待不会在控制台中抛出错误

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

MDN says : MDN说

Remember, the await keyword is only valid inside async functions. 请记住, await关键字仅在async函数内有效。 If you use it outside of an async function's body, you will get a SyntaxError . 如果在async函数体外使用它,则会出现SyntaxError

But that's not true. 但事实并非如此。

Try this code in DevTools console, no errors, just result: 在DevTools控制台中尝试此代码,没有错误,只是结果:

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. MDN文档是正确的,它解释了它在JavaScript中的工作原理。

This is just a feature added by the DevTools for making you easier to test async/await code. 这只是DevTools添加的一项功能,可让您更轻松地测试异步/等待代码。 And it is not a JavaScript feature. 它不是JavaScript功能。

It looks like it has been supported since 11/08/2017 in DevTools: 看起来它自2017年8月11日起在DevTools中得到支持:

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

If you spy the 如果你间谍了

ConsoleModel.js ConsoleModel.js

at line 129, they have the function for evaluating expressions marked as async: 在第129行,它们具有评估标记为异步的表达式的功能:

async evaluateCommandInConsole

Nothing is wrong. 没有错误。

You've found a special feature of the DevTools console ! 您已经找到了DevTools控制台的一个特殊功能 It is there to make it as easy as possible to experiment with async - await code in a live environment. 它是让尽可能简单的实验async - await实时环境中的代码。 You can imagine that any code you enter in the console is wrapped in an async function automatically. 您可以想象您在控制台中输入的任何代码都会自动包装在async函数中。 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. 重要的是要注意,即使这在控制台中有效,它也不是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. MDN文档是准确的,因为如果您尝试在async函数之外使用await的页面上加载脚本,则会出错。 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. 另一方面,DevTools控制台旨在使其工作(专门用于开发人员工效学),因此您的代码在控制台中运行时没有任何错误。

This isn't the only trick the DevTools console has up its sleeve . 这不是DevTools控制台的唯一技巧 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. 通常,如果您真的想测试某些代码在页面上的运行方式,那么最好在页面上实际运行脚本,而不是在控制台中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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