There is class A , the creation of an instance of which runs some kind of "background" processes. These processes generate events to which you can "subscribe".

 class A { constructor() { // ... } } let a = new A(); a.when.ready.then(() => { console.log("ready"); }); 

To do this, I created a static registerEventResolvers method, which I use in the constructor

 class A { static registerEventResolvers(instance) { instance.when = {}; // сюда помещаем зарегистрированные события, на которые можно "подписываться" с помощью `when` instance.resolvers = {}; // а сюда будем сохранять резолверы промисов, чтобы их [промисы] можно было резолвить извне let registerEventResolver = (event) => { // функция, которая вызывается ниже let promise = new Promise(res => { // создаем промис instance.resolvers[event] = res; // а резолвер помещаем в свойство `resolvers` инстанса, т.е. чтобы можно было вызывать `a.resolvers["ready"]()` }); promise.then(() => { // (*) вот тут ключевой момент registerEventResolver(event); }); instance.when[event] = promise; // сохраняем, чтобы можно было делать `a.when.ready.then()` }; [ // список известных (разрешенных) событий, на которые можно будет подписываться "ready", "error", // "..." ].forEach(event => { registerEventResolver(event); // для каждого из них сохраняем резолвер }); } constructor() { A.registerEventResolvers(this); } } 

Overall, it works.

 class A { static registerEventResolvers(instance) { instance.when = {}; instance.resolvers = {}; let registerEventResolver = (event) => { let promise = new Promise(res => { instance.resolvers[event] = res; }); promise.then(() => { registerEventResolver(event); }); instance.when[event] = promise; }; [ "ready", "error", ].forEach(event => { registerEventResolver(event); }); } constructor() { A.registerEventResolvers(this); // ... this.resolvers["ready"](); } } let a = new A(); a.when.ready.then(() => { console.log("ready"); }); 

However, the problem occurs when I re-throw the same event - it just does not work

 class A { static registerEventResolvers(instance) { instance.when = {}; instance.resolvers = {}; let registerEventResolver = (event) => { let promise = new Promise(res => { instance.resolvers[event] = res; }); promise.then(() => { registerEventResolver(event); }); instance.when[event] = promise; }; [ "ready", "error", ].forEach(event => { registerEventResolver(event); }); } constructor() { A.registerEventResolvers(this); // ... this.resolvers["ready"](); this.resolvers["ready"](); } } let a = new A(); console.log("Подписались один раз, но заэмиттили дважды, поэтому должно вывести \"ready\" 2 раза, но выводит только 1"); a.when.ready.then(() => { console.log("ready"); }); 

The fact that the promise cannot go from settled state to pending again is as clear as day. That is why I added these lines, which replace the promise with fresh one after it has cut off (so that it’s possible (well, as if it weren’t his, but the other)

 promise.then(() => { // (*) вот тут ключевой момент registerEventResolver(event); }); 

I thus expected that when the promise was cleared, it would simply be replaced by the newly created one and when it was called again, the resolver would work the same then , which had already been hung on the instance from outside. But this is not happening.

Why so, I do not quite understand. And this is the first thing that interests. 2nd , obviously, what to do with it (if anything is possible at all).

I would venture to suggest that the problem can be solved in some way with the help of generators, but I’m not sure, so I don’t want to waste time in order to gobble up again. So please help.

  • Why pull an owl on a globe? You just need to take the EventEmitter nodejs.org/api/events.html - Alexey Ten
  • @AlexeyTen is not a node :) In general, I agree that the architecture of the event emitter (in my implementation of this kind) is rather doubtful, so I am ready to listen to other suggestions. But I would like to first get my code to work (if possible) to figure out what's what - smellyshovel
  • @AlexeyTen or wait, what am I, can I get the nodovskaya lib in the browser to pull out? O_O - smellyshovel
  • As I recall it is written in js. Well, in npm there are analogues, I suppose. I did not mean to take exactly the nodovsky, I mean, what you really want is not a promise, but just the same events - Alexey Ten
  • It will not work because a.when.ready.then() refers to the first promise. Try to figure out the Pub / Sub pattern. - sneas

0