多个未连接的异步事件如何等待单个承诺

Mar*_*ler 5 javascript async-await

我有一个系统,我需要来自服务器的 id 来处理事件。我应该只在第一个事件发生时获取 id,但之后,我需要为每个后续事件使用相同的 id。我知道如何使用 async-await 等,所以我有一些这样的代码

var id = "";
async function handleEvent(e) {
    if (! id ) {
        let response = await fetch(URL)
        if (response.ok) { 
            let json = await response.json();
            id = json.id ;
        }
    }
    // use id to handle event
}
Run Code Online (Sandbox Code Playgroud)

但我的问题是,在收到响应之前我可能会收到多个事件,因此我会收到多个重叠的调用来获取新的 id。

如何对handleEvent进行多个异步调用,第一个调用处理获取,任何后续调用等待它完成以访问结果?

Mar*_*ler 0

事实证明,这个问题的解决方案与之前的答案略有不同。我想我会发布我最终是如何让它发挥作用的。@phil 和 @vaelin 的答案确实帮助我解决了这个问题。

这是我的解决方案......

class IDManager {
    async fetchID (resolve,reject ) {
        const response = await fetch( URL, { } ) ;
        const id = await response.json() ;
        resolve( id );
    }
    async getID() {
        if ( this.id === undefined ) {
            if ( this.promise === undefined ) {
                var self = this;
                this.promise = new Promise( this.fetchID ).then( function(id) { self.id = id;} );
            }
            await this.promise;
        }
        return this.id;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是等待获取 getID 调用需要花费几秒钟。在此期间,经常会多次调用 getID,所有这些都会启动另一次获取。我通过将 fetch 和 response.json 调用包装在另一个立即创建的 Promise 中来避免这种情况,从而避免了重复。