Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there native support for promises in current versions of Node.js?

Node.js uses the V8 engine. This JavaScript engine is also used by Chrome, and Chrome 32 has native support for promises. But I can't seem to get promises to work (natively) in Node.js.

I've tried the following code in Chrome 32 and it works.

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if ( 1===1 /* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

promise.then(function( message ) {
  console.log( message );
},
function( err ) {
  console.log( err );
});

However, when I try this same code in Node.js, I get:

var promise = new Promise(function(resolve, reject) {
                   ^
ReferenceError: Promise is not defined

This code is from the excellent tutorial:

http://www.html5rocks.com/en/tutorials/es6/promises/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

Although Node.js added native promise in stable version 0.12.

But due to the memory leak issue, I recommend to use bluebird to avoid the issue.


Old anwser:

Node.js added native promise support since version 0.11.13.

nvm install 0.11.12
nvm run 0.11.12
> Promise
ReferenceError: Promise is not defined
> console.log(process.versions.v8)
3.22.24.19

nvm install 0.11.13
nvm run 0.11.13
> Promise
[Function: Promise]
> console.log(process.versions.v8)
3.25.30

Note: Node.js v0.11 is still in beta, be careful if use it in production.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...