简体   繁体   English

NodeJS关于Promises的最佳实践

[英]NodeJS best practices with Promises

I am developing a new library above amqp.node (amqplib), basically we dont need all the RabbitMQ functionality. 我正在amqp.node(amqplib)之上开发一个新的库,基本上我们不需要所有RabbitMQ功能。 So, I am creating a simple library that facilitates the usage specifically for our project. 因此,我正在创建一个简单的库,该库专门用于我们的项目。

This new library will return Promises. 这个新库将返回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). 因此,如果您可以先断开连接,然后重新连接,再断开连接,等等...您要么必须为每个状态转换创建一个新的Promise,否则Promise并不是最简单的实现,而您真正想要的是只是使侦听器订阅各种事件的能力(从eventEmitter派生并发出其他人可以收听的有趣事件)。

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 JavaScript异步体系结构:事件与承诺

Event Emitter, Pub Sub or Deferred Promises … which should you choose? 事件发射器,Pub Sub或Deferred Promises…您应该选择哪个?

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. 您也可以参考或使用这些-> q承诺库 ,该是在上述准则的基础上创建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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