为处理事件的常规诺言命名为诺言

问题描述

我正在尝试创建一个命名的诺言链。我不确定如何实现这一目标。目标是:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.4.0-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j</artifactId>
            <version>6.0.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</dependencyManagement>

我已经读过这篇文章,但这并不能完全解决目的。 Handling multiple catches in promise chainhttps://javascript.info/promise-chaining

不想使用Rx并希望保留原始js

解决方法

使用Promises不能实现类似的目标。
取而代之的是,您可以使用返回事件注册器的函数来创建一个返回对象的函数。

这是一个简单的例子:

function test() {
  return new (function() {
    this.eh = {};
    
    this.on = (event,handler) => {
      this.eh[event] = handler;
      return this;
    }
    
    this.call = (event,...args) => {
      if (typeof this.eh[event] === 'function') {
        this.eh[event](...args);
      }
    }
    
    Promise.resolve().then(() => {
      // Do your stuff...
      
      // Example:
      this.call('msg','This is a message.');
      setTimeout(() => {
        this.call('some-event','This is some event data.');
        
        this.call('error','This is an error.');
      },1000);
      
    });
  })()
}

test()
  .on('msg',(msg) => console.log(`Message: ${msg}`))
  .on('some-event',(data) => console.log(`Some event: ${data}`))
  .on('error',(err) => console.log(`Error: ${err}`))

我希望那是你的工作。

修改:
这是另一种尝试:https://jsfiddle.net/bg7oyxau/