AsyncFunction is not defined, yet MDN documents it's usage

为君一笑 提交于 2019-12-11 17:28:23

问题


There is an article AsyncFunction - JavaScript on MDN. It shows the following snippet:

new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)

Yet in both Mozzila Firefox 55 and Google Chrome, this constructor is not defined at all:

I found out that (async function() {}).constructor really is AsyncFunction, but why can't I see it in global scope?


回答1:


As mentioned in the Mozilla docs "Note that AsyncFunction is not a global object."

Therefore you can't access it as a property of the window object like other global constructors. It must be obtained by interrogating an instance of an async function:

From the docs:

const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;



回答2:


The documentation itself is confused so it's no wonder that people get confused as well.

MDN docs tell us that AsyncFunction is not a global object, and yet they list it in the Global Objects reference! Oops!

  • https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/AsyncFunction

This leads to unexpected behavior. This works:

> f1 = function () {};
[Function: f1]
> f1 instanceof Function
true

But this doesn't:

> f2 = async function () {}
[AsyncFunction: f2]
> f2 instanceof AsyncFunction
ReferenceError: AsyncFunction is not defined

I wrote an unexposed module that you can use:

  • https://www.npmjs.com/package/unexposed

It basically works like the example in the answer by Patrick but you don't have to remember it.

See also this question for more info:

  • How to know if a function is async?


来源:https://stackoverflow.com/questions/46118496/asyncfunction-is-not-defined-yet-mdn-documents-its-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!