一次使用承诺的事件处理? [英] One time event handling using promises?

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

问题描述

几乎平常的情况。我想要有一些去耦的代码,那就是当事情准备就绪时触发事件。这将在整个应用程序运行中发生一次。另一方面,另外还有一段代码,当两个或多个事件被触发时,我想要再发生一些事情。我的意思是像他们所有的一样,像依赖关系。



好吧,更多异步的东西在一起...肯定是承诺吗?



然后我开始思考使用pub / sub进行一次性活动是否真的很明智?一旦这个事件即将被触发,解决方案就不会更好吗?然而,这意味着我需要连接这个去耦代码。有一件事是共享EventEmitter,而是依赖于一些代码来实际创建promise ...这听起来很糟糕。



所以我在想一些混合。拥有模块,其他模块可以通过其名称请求事件,并获得准备好的Promise对象。其他模块应该触发该事件,并以这种方式有效地实现/拒绝该事件。

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

你对这个解决方案有什么看法?任何机会都有这样的解决方案已经可以使用?

解决方案

好的,我已经做出了我自己的解决方案这个问题。



欢迎使用应许之地


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 ?

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.

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.

Welcome to the Promised Land

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

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