Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Promises in Node 4.x?

Now that ES6 is officially standard in Node 4.x, how do you use Promises? Do modules (for example the native fs module) automatically work with Promises? Or modules have to be written specifically to work with Promises? How do you know what you can use a Promise with and what you can't?

There have been so many different Promise implementations (Q, Bluebird, etc) that I am confused on where to start with native Promises in Node 4.x.

like image 951
Jake Wilson Avatar asked Sep 29 '15 04:09

Jake Wilson


1 Answers

how do you use Promises?

You can use "native" promises by using the new constructor, Promise. The basics of the API can be found over on MDN, and an in-depth study of Promises can be found on HTML5Rocks.

Do modules (for example the native fs module) automatically work with Promises?

They do not, but it's not so difficult to make a wrapper. Of course, doing this for the whole Node API could be a bit tedious.

One of the comments in the OP mentioned Bluebird's PromisifyAll, which seems like a magic way to convert an entire module to use Promises. Nifty!

I would expect some Promise-ified APIs in coming versions of Node, but I'm not certain of this. There might be an issue or discussion somewhere around this...perhaps on the io.js project. I'll investigate and update this if I find anything.

As for why we have Promises and a callback-style API? That's likely because of the fact that it's easier to be additive, adding Promises, than it is to make possibly breaking API changes, like removing callbacks.

Or modules have to be written specifically to work with Promises?

They do.

How do you know what you can use a Promise with and what you can't?

The documentation is always the best place to go for API questions. I don't know of anything that returns Promises, but I admittedly use a small subset of the Node API in my day-to-day.

There have been so many different Promise implementations (Q, Bluebird, etc) that I am confused on where to start with native Promises in Node 4.x.

Do you have any specific questions about these different implementations? The way I think about it is that native Promises are pretty minimal. They're good enough to make asynchronous code a little bit cleaner, but they have no frills. Those other libraries you mention do two things:

  1. Provide a Polyfill for environments that don't support native Promises
  2. add varying degrees of fancy features

The first use case is no longer necessary in Node. So it's a matter of determining if you want/need any of those fancy features.

Let me know if this answer isn't satisfactory, and I'll try to update it with more info!

like image 116
jamesplease Avatar answered Sep 21 '22 00:09

jamesplease