node.js Node 7.1.0 new Promise() 解析器 undefined 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40561915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node 7.1.0 new Promise() resolver undefined is not a function
提问by lars1595
I'm using the latest node version 7.1.0 on OSX but I still can't use Promises. I get
我在 OSX 上使用最新的节点版本 7.1.0,但我仍然无法使用 Promises。我得到
index.js
索引.js
new Promise();
Error:
错误:
new Promise(); ^TypeError: Promise resolver undefined is not a function
new Promise(); ^类型错误:未定义的承诺解析器不是函数
Doesn't node 7.1.0 support ES6 and Promise?
node 7.1.0 不支持 ES6 和 Promise 吗?
回答by Benjamin Gruenbaum
The API for promises requires you to pass a function to the promise constructor. Quoting MDN:
Promise 的 API 要求您将函数传递给 Promise 构造函数。引用MDN:
new Promise( /* executor */ function(resolve, reject) { ... } );
executor- A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise respectively. The executor normally initiates some asynchronous work and then, once that completes, calls either the resolve or reject function to resolve the promise or else reject it if an error occurred.
new Promise( /* executor */ function(resolve, reject) { ... } );
executor- 一个带有参数 resolve 和 reject 的函数。执行器函数由 Promise 实现立即执行,传递解析和拒绝函数(在 Promise 构造函数甚至返回创建的对象之前调用执行器)。resolve 和 reject 函数在调用时分别解析或拒绝承诺。执行器通常会启动一些异步工作,然后,一旦完成,调用 resolve 或 reject 函数来解决承诺,否则如果发生错误则拒绝它。
You can see this answerfor usage examples.
您可以查看此答案以获取使用示例。
Node 7.1 supports promises.
Node 7.1 支持承诺。
回答by bpinhosilva
You must provide the callbacks to Promise constructor so it'll know what to do when resolving or rejecting the operation.
您必须向 Promise 构造函数提供回调,以便它知道在解决或拒绝操作时要做什么。
For example:
例如:
var p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 5000);
});
p.then(() => {
console.log("Got it");
})
After 5 seconds you'll see the message Got itin your console.
5 秒钟后,您将Got it在控制台中看到该消息。
There is a very good library for Promises: Bluebird
Promises 有一个非常好的库:Bluebird
Check the MDNdocumentation as well.
还要检查MDN文档。
I like this article from Google developers.
我喜欢这篇来自Google 开发者的文章。
回答by Aymeric Bouzy aybbyk
You cannot create a new Promise this way without providing some argument. You can however create a promise that resolves to undefinedsimply by using Promise.resolve().
你不能在不提供一些参数的情况下以这种方式创建一个新的 Promise。但是,您可以创建一个undefined简单地使用Promise.resolve().

