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 20:16

Another advantage of promises is that error handling and exception throwing and catching is much better than trying to handle that with callbacks.

The bluebird library implements promises and gives you great long stack traces, is very fast, and warns about uncaught errors. It also is faster and uses less memory than the other promise libraries, according to http://bluebirdjs.com/docs/benchmarks.html

查看更多
十年一品温如言
3楼-- · 2019-01-02 20:18

This new tutorial on Promises from the author of PouchDB is probably the best I've seen anywhere. It wisely covers the classic rookie mistakes showing you correct usage patterns and even a few anti-patterns that are still commonly used - even in other tutorials!!

Enjoy!

PS I didn't answer some other parts of this question as they've been well covered by others.

查看更多
登录 后发表回答