参考Promise.All

发布于 2025-02-04 20:24:36 字数 348 浏览 1 评论 0 原文

此代码有效:

Promise.all([Promise.resolve(1)])

但是,此代码不:

const f = Promise.all

f([Promise.resolve(1)])

第二件代码列出以下错误: und offerate typeerror:Promise.All in non-object

为什么我不能将函数承诺分配给变量并正常使用?

This code works:

Promise.all([Promise.resolve(1)])

However, this code does not:

const f = Promise.all

f([Promise.resolve(1)])

The second piece of code throws the following error: Uncaught TypeError: Promise.all called on non-object.

Why can't I assign the function Promise.all to a variable and use it as normal?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无悔心 2025-02-11 20:24:37

因为那是规格要求

1. Let C be the this value.
2. Let promiseCapability be ? NewPromiseCapability(C).
3. Let promiseResolve be Completion(GetPromiseResolve(C)).
...

所有函数要求其值是支持Promise构造器参数约定的构造函数。

您当前的代码不是将函数称为对象的一部分(即, f 是独立标识符),因此结果是全局对象或 >未定义的,取决于您是否处于严格模式 - 无论哪种方式,上述要求都无法满足。

如果将功能绑定到承诺,它将起作用。

const f = Promise.all.bind(Promise);

Because that's what the spec requires.

1. Let C be the this value.
2. Let promiseCapability be ? NewPromiseCapability(C).
3. Let promiseResolve be Completion(GetPromiseResolve(C)).
...

The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

Your current code is not calling the function as part of an object (that is, f is a standalone identifier), so the resulting this is either the global object or undefined, depending on whether you're in strict mode or not - either way, the above requirement is not fulfilled.

If you bind the function to Promise, it'll work.

const f = Promise.all.bind(Promise);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文