简体   繁体   中英

NodeJS best practices with Promises

I am developing a new library above amqp.node (amqplib), basically we dont need all the RabbitMQ functionality. So, I am creating a simple library that facilitates the usage specifically for our project.

This new library will return Promises. So, for example, subscribing to a queue will return a Promise about Ok and Error. But, what should I do with later issues? Disconnect, reconnect, Queue deleted, etc, etc? This will happen after the promise has been resolve. Should my new class emit his own errors? Is this a good way of working with promises?

Promises are one shot devices. So, they are only the right design tool for a one time state transition. Once they've been resolved or rejected, they are locked into that state. After that, you either have to have new promises for new operations or promises aren't really the right scheme and you'd rather have something like event notification.

So, if you can have a disconnect, then a reconnect, then a disconnect, etc... you'll either have to create a new promise for each state transition or promises aren't really the simplest implementation and what you really want is just an ability to subscribe listeners to various events (derive from an eventEmitter and emit interesting events that others can listen to).

I don't claim to understand exactly what you're trying to build, but several parts of your description sound like maybe you want more of an event notification scheme for much of your project instead of promises.

FYI, here are some interesting articles on the different notification schemes:

Callbacks, Promises, Signals and Events

JavaScript Asynchronous Architectures: Events vs. Promises

Event Emitter, Pub Sub or Deferred Promises … which should you choose?

Here are the guidelines you can follow to implement promises:

Promise Guidelines

Also you can refer or use these -> q promise library which is created on the basis if above guidelines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM