在继续之前等待 Typsescript 中的自定义事件

问题描述 投票:0回答:1

我有一个功能:

async ready():Promise<boolean> { await this.myClass.firstToComplete(); this.myClass.secondToComplete(); }
但是firstToComplete()需要等待它正在侦听的事件才能继续。

async firstToComplete(): Promise<void>{ return new Promise(resolve =>  this.anEventListener = () => resolve()); 

但我不确定如何正确构建它。

这是我当前代码库的摘要:

async ready():Promise<boolean> { await this.myClass.firstToComplete(); this.myClass.secondToComplete(); }

`导出类 myClass{ 私有静态completion_event = new Event(“完成”);

async anEventListener(): Promise<void>{
    await window.addEventListener("complete", function(){
        return
    });
}

async firstToComplete(): Promise<void> {
     await this.listening();


async listening() {
    return new Promise(resolve =>  this.anEventListener = () => resolve());
}

private static functionWaitingToComplete() {
    window.dispatchEvent(this.completion_event)
}

`

angular typescript asynchronous events
1个回答
0
投票

我对事件和 Promise 没有太多经验,但在我看来,有两种选择,一种是解决事件中的 Promise,另一种是将第二个函数作为回调传递

第一个选项是这样的:

const firstFunction = () => {
  return new Promise((resolve, reject) => {
    const onMyEvent= () => {
      resolve("Event occured");
    };

    window.addEventListener("eventName", onMyEvent);
  });
};

const secondFunction = () => {
  console.log("After first function event");
};

const asyncFunction = async () => {
  await firstFunction();
  secondFunction();
};

第二个选项是这样的:

const firstFunction = (callback: () => void) => {
    const onMyEvent= () => {
      callback();
    };

    window.addEventListener("eventName", onMyEvent);
  });
};

const secondFunction = () => {
  console.log("After first function event");
};

const asyncFunction = async () => {
  await firstFunction(secondFunction);
};
© www.soinside.com 2019 - 2024. All rights reserved.