我有一个功能:
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)
}
`
我对事件和 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);
};