Ad

How Can Multiple Unconnected Async Events Await A Single Promise

- 1 answer

I have a system where I need an id from a server to handle events. I should only fetch the id if/when the first event happens, but after that, I need to use the same id for each subsequent event. I know how to use async-await etc. so I have some code like this

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
}

But my problem is that I could receive multiple events before I receive a response, so I get multiple overlapping calls to fetch a new id.

How can I have multiple asynchronous calls to handleEvent, with the first one processing the fetch and any subsequent call waiting for it to complete to access the result?

Ad

Answer

The solution to this turned out to be a little different from the previous answers. I thought I would post how I made it work in the end. The answers from @phil and @vaelin really helped me to figure this out.

Here was my solution...

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;
    }
}

The problem was that awaiting the fetch the getID call took a couple of seconds. During that time there were often multiple calls to getID, all of which initiated another fetch. I avoided that by wrapping the fetch and response.json calls in another promise which was created instantly, and so avoided the duplicates.

Ad
source: stackoverflow.com
Ad