Friday, 25 March 2022

Passing a promise in a Custom Event detail

I'm trying to pass a promise object via a Custom Event's detail property.

scriptA.js

async function myFunc() {...}

document.addEventListener('eventA', function (event) {
    const outputEvent = new CustomEvent('eventB', { detail: { promise: myFunc() } });
    document.dispatchEvent(outputEvent);
});

scriptB.js

document.addEventListener('eventB', async function (event) {
    const { promise } = event.detail;
    const result = await promise;
    console.log('result', result);
});

Then I try to call this (either from scriptB or from a 3rd unrelated script, after both scriptA and scriptB were loaded):

document.dispatchEvent(new CustomEvent('eventA'));

When I print the detail object in scriptA before dispatching the event, it shows the promise object correctly, but it doesn't arrive to to scriptB at all - the detail property arrives as null.

Am I missing something here?


When I create a sandbox to replicate it, it works fine.

However, in my actual code, it doesn't. here are screenshots from Chrome debugger:

In the dispatch part: enter image description here enter image description here

In the listener part: enter image description here

If I don't include the response (which is a Promise object) in the dispatched detail, everything arrives correctly.



from Passing a promise in a Custom Event detail

No comments:

Post a Comment