JavaScript 中 Promise.resolve is not a constructor 错误
当我们尝试将 Promise.resolve()
方法与 new
运算符一起使用时,会出现“Promise.resolve is not a constructor”错误。 Promise.resolve()
方法不是构造函数,因此应该在没有 new 运算符的情况下使用它,例如 Promise.resolve('example')
。
下面是一个产生上述错误的示例代码
// ⛔️ Promise.resolve is not a constructor
const err = new Promise.resolve('example');
相反,我们不应该将 new 运算符与 Promise.resolve
方法一起使用。
// ✅ works
const resolved = Promise.resolve('example');
Promise.resolve
是一种方法,而不是构造函数。 该方法采用的唯一参数是要由 promise 解析的值。
Promise.resolve()
方法返回一个由提供的值解决的承诺。
请注意
,与Promise.resolve
方法相反,Promise()
是一个构造函数,用于包装尚不支持承诺的函数。
以下 2 个示例实现相同的结果:
const r1 = Promise.resolve('example');
const r2 = new Promise((resolve, reject) => {
resolve('example');
});
这两个变量都存储了一个已实现的 promise
,但是,对于这个用例,Promise.resolve
方法为我们提供了比 Promise()
构造函数更直接和简洁的解决方案。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。