Search code examples
javascripteventspromise

Wait for both promise and event listener in JavaScript


This is probably a simple problem, but I can't figure out how to do this.

I need to run code when the page is loaded and a promise is resolved. Since the promise is a bit long, I want to start the promise first. Here is my code:

// Wait for the promise
myLongFunction().then(() => {
            
    // Wait for the page to be load and rendered
    window.addEventListener('load', (event) => {

        // I do awesome stuff here
    });
});

Sometimes, when myLongFunction() is too long, the DOM is already loaded and the event has already been triggered. I never do my awesome stuff.

The following always works:

// Wait for the page to be load and rendered
window.addEventListener('load', (event) => {

    // Wait for the promise
    myLongFunction().then(() => {

        // I do awesome stuff here
    });  
});

I prefer the first option since myLongFunction() is running while the DOM is loaded. Is there a way to wait for both event properly?


Solution

    • Have a promise resolve when the load event fires.
    • Use Promise.all to wait for them both.

    e.g.

    
    const loadPromise = new Promise((resolve) => {
        addEventListener('load', resolve);
    });
    
    const otherPromise = myLongFunction();
    
    Promise.all([loadPromise, otherPromise]).then((results => {
        // Both promises have now resolved
    });