Search code examples
javascriptjqueryeventsasync-awaitlistener

How to await ALL of the Listeners execution for Custom jQuery Event?


$(document).on('custom-event', listener1 );
$(document).on('custom-event', listener2 );

function listener1() {
    return new Promise((resolve) => {
        setTimeout(resolve, 3000);
    })
}

function listener2() {
    return new Promise((resolve) => {
        setTimeout(resolve, 10000);
    })
}


$(document).trigger('custom-event');
const afterAwaiting = true; // Need to await 10 seconds after previous line of code to execute this statement

I've triggered custom Event - custom-event.

Need to await All of the Listeners execute its code,

then continue to execute next statement.


Solution

  • I've found solution by using when.

    await $.when( $(document).trigger('custom-event') )
    
    const afterAwaiting = true;
    

    jQuery runs Custom Events Synchronously according to the question

    jQuery trigger custom event synchronously?

    Or it works even without await

    $(document).trigger('custom-event')