30

I'm using the latest node version 7.1.0 on OSX but I still can't use Promises. I get

index.js

new Promise();

Error:

new Promise();
             ^

TypeError: Promise resolver undefined is not a function

Doesn't node 7.1.0 support ES6 and Promise?

Soviut
  • 88,194
  • 49
  • 192
  • 260
lars1595
  • 886
  • 3
  • 12
  • 27
  • Show your code. Create a [minimal, complete and verifyable example](https://stackoverflow.com/help/mcve) – try-catch-finally Nov 12 '16 at 11:25
  • 6
    You have to pass a parameter to `new Promise()`. You are passing nothing, which is treated as `undefined`, which is not a function, hence the error. The function you pass is usually called a "resolver", so the error message would be more helpful if it said "Promise executor undefined is not a function". –  Nov 12 '16 at 12:53
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – str Nov 12 '16 at 13:00
  • 1
    That doesn't work even on Node 6. You can try this `new Promise(() => {});`, which is also wrong, but won't give an error. – goenning Nov 12 '16 at 13:02
  • Yes, node 7 has support for Promises. It's being developed since 0.12.17 according to this [page](http://node.green/). – bpinhosilva Nov 13 '16 at 16:17

3 Answers3

30

The API for promises requires you to pass a function to the promise constructor. Quoting 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.

You can see this answer for usage examples.

Node 7.1 supports promises.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
29

You must provide the callbacks to Promise constructor so it'll know what to do when resolving or rejecting the operation.

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 it in your console.

There is a very good library for Promises: Bluebird

Check the MDN documentation as well.

I like this article from Google developers.

bpinhosilva
  • 692
  • 1
  • 5
  • 15
1

You cannot create a new Promise this way without providing some argument. You can however create a promise that resolves to undefined simply by using Promise.resolve().

Aymeric Bouzy aybbyk
  • 2,031
  • 2
  • 21
  • 29