Understanding promises in node.js

2019-01-02 19:37发布

From what I have understood there are three ways of calling asynchronous code:

  1. Events: eg. request.on("event", callback);
  2. Callbacks: eg. fs.open(path, flags, mode, callback);
  3. Promises

I found a promise library https://github.com/kriszyp/node-promise but I don't get it.

Could someone explain what promises are all about and why I should use it?

Also, why was it removed from Node.js?

8条回答
残风、尘缘若梦
2楼-- · 2019-01-02 19:56

Mike Taulty has a series of videos, each of them less than ten minutes long, describing how the WinJS Promise library works.

These videos are quite informative, and Mike manages to show the power of the Promise API with a few well-chosen code examples.

var twitterUrl = "http://search.twitter.com/search.json?q=windows";
var promise = WinJS.xhr({ url: twitterUrl });

 promise = promise.then(
     function (xhr) {
     },
     function (xhr) {
         // handle error
     });

The treatment of how exceptions are dealt with is particularly good.

In spite of the WinJs references, this is a general interest video series, because the Promise API is broadly similar across its many implementations.

RSVP is a lightweight Promise implementation that passes the Promise/A+ test suite. I quite like the API, because it is similar in style to the WinJS interface.

Update Apr-2014

Incidentally, the WinJS library is now open source.

查看更多
泪湿衣
3楼-- · 2019-01-02 20:02

Since this question still has many views (like mine) I wanted to point out that:

  1. node-promise looks rather dead to me (last commit was about 1 year ago) and contains nearly no tests.
  2. The futures module looks very bloated to me and is badly documented (and I think that the naming conventions are just bad)
  3. The best way to go seems to be the q framework, which is both active and well-documented.
查看更多
还给你的自由
4楼-- · 2019-01-02 20:04

A promise is a "thing" which represents the "eventual" results of an operation so to speak. The point to note here is that, it abstracts away the details of when something happens and allows you to focus on what should happen after that something happens. This will result in clean, maintainable code where instead of having a callback inside a callback inside a callback, your code will look somewhat like:

 var request = new Promise(function(resolve, reject) {
   //do an ajax call here. or a database request or whatever.
   //depending on its results, either call resolve(value) or reject(error)
   //where value is the thing which the operation's successful execution returns and
   //error is the thing which the operation's failure returns.
 });

 request.then(function successHandler(result) {
   //do something with the result
 }, function failureHandler(error) {
  //handle
 });

The promises' spec states that a promise's

then

method should return a new promise that is fulfilled when the given successHandler or the failureHandler callback is finished. This means that you can chain together promises when you have a set of asynchronous tasks that need to be performed and be assured that the sequencing of operations is guaranteed just as if you had used callbacks. So instead of passing a callback inside a callback inside a callback, the code with chained promises looks like:

var doStuff = firstAsyncFunction(url) {
                return new Promise(function(resolve, reject) {
                       $.ajax({
                        url: url,
                        success: function(data) {
                            resolve(data);
                        },
                        error: function(err) {
                             reject(err); 
                        } 
                  });
               };
doStuff
  .then(secondAsyncFunction) //returns a promise
  .then(thirdAsyncFunction); //returns a promise

To know more about promises and why they are super cool, checkout Domenic's blog : http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/

查看更多
不流泪的眼
5楼-- · 2019-01-02 20:04

What exactly is a Promise ?

A promise is simply an object which represents the result of an async operation. A promise can be in any of the following 3 states :

pending :: This is the initial state, means the promise is neither fulfilled nor rejected.

fulfilled :: This means the promise has been fulfilled, means the value represented by promise is ready to be used.

rejected :: This means the operations failed and hence can't fulfill the promise. Apart from the states, there are three important entities associated to promises which we really need to understand

  1. executor function :: executor function defines the async operation which needs to be performed and whose result is represented by the promise. It starts execution as soon as the promise object is initialized.

  2. resolve :: resolve is a parameters passed to the executor function , and in case the executor runs successfully then this resolve is called passing the result.

  3. reject :: reject is another parameter passed to the executor function , and it is used when the executor function fails. The failure reason can be passed to the reject.

So whenever we create a promise object, we've to provide Executor, Resolve and Reject.

Reference :: Promises

查看更多
笑指拈花
6楼-- · 2019-01-02 20:10

I've been also looking into promises in node.js recently. To date the when.js seems to be the way to go due to its speed and resource use, but the documentation on q.js gave me a lot better understanding. So use when.js but the q.js docs to understand the subject.

From the q.js readme on github:

If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.

查看更多
千与千寻千般痛.
7楼-- · 2019-01-02 20:14

Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.

The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).

By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.

查看更多
登录 后发表回答