使用 Promise 进行一次性事件处理? [英] One time event handling using promises?

查看:18
本文介绍了使用 Promise 进行一次性事件处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常常见的场景.我想要一些解耦的代码,即在准备就绪时触发事件.对于整个应用程序运行,这只会发生一次.

Pretty much usual scenario. I want to have some decoupled piece of code, that is triggering event when something is ready. This will happen only once for the whole application run.

另一方面,还有另一段代码,我希望在触发两个或多个事件时发生其他事情.我的意思是像所有这些一样,像依赖一样.

On other side, there is another piece of code, where I want something else to happen when two or more events are triggered. I mean like all of them, like dependencies.

好吧,更多的异步事情在一起......肯定是对的吗?

Alright, more async things together ... definitely promises right ?

然后我开始思考.将 pub/sub 用于一次性事件真的明智吗?做出可访问的承诺不是更好,一旦该事件即将被触发就解决了吗?但是,这意味着我需要将分离的代码互连起来.一件事是共享 EventEmitter,但依赖于一些代码来实际创建承诺......这听起来很糟糕.

Then I started thinking. Is it really wise to use pub/sub for one time events ? Wouldn't be better to just make accessible promise, that resolves once that event is about to be triggered ? However that would mean I need to kinda interconnect that decoupled code. One thing is having shared EventEmitter, but being dependent on some code to actually create promise ... that sounds rather bad.

所以我在考虑某种混合.拥有模块,其他模块可以通过它的名称请求事件"并获得准备好的 Promise 对象.然后其他模块应该触发该事件并以这种方式有效地实现/拒绝该事件.

So I am thinking about some kind of mix. Having module, where other modules can ask for "event" by it's name and obtaining prepared Promise object. Other module should then trigger that event and effectively fulfilling/rejecting that event this way.

var promisedLand = require('./promisedLand');
promisedLand.waitFor('event'); // returns promise
promisedLand.resolve('event', value);
promisedLand.reject('event', error);

您如何看待这个解决方案?有没有可能已经有这样的解决方案?

What do you think about this solution ? Any chance there is some solution like this already available ?

推荐答案

好吧,我已经制定了自己的解决方案,类似于问题中提出的解决方案.

Alright, I have made my own solution similar to the one presented in the question.

欢迎来到应许之地

这篇关于使用 Promise 进行一次性事件处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆