'Passing a promise in a Custom Event detail
I'm trying to pass a promise object via a Custom Event's detail property.
The custom event is passed between two scripts which are not sharing the same global context - one is an extension's content script and the other is the main website script.
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:
If I don't include the response (which is a Promise object) in the dispatched detail, everything arrives correctly.
Solution 1:[1]
First, thanks for the sandbox - it truly speeds things up and made it clear what you are currently facing
To the point
async function myFunc() {...}
document.addEventListener('eventA', function (event) {
const outputEvent = new CustomEvent('eventB', { detail: { promise: myFunc() } });
document.dispatchEvent(outputEvent);
});
I think that the problem is here
{ detail: { promise: myFunc() } }
Here you are attach the invokes promise.. why not assign the delegation only?
{ detail: { promise: myFunc } }
The meaning of this line is: assign the reference to my promise but son't invoke it (yet). It seems to be your original intention since youe later on used this code
document.addEventListener('eventB', async function (event) {
const { promise } = event.detail;
const result = await promise;
console.log('result', result);
});
which supposed to be
const { promise } = event.detail; // promise here is the delegation to your function
const result = await promise(); // properly invoke it and wait for it's result
To my understating.. you can't invoke a promise in one code block and await result in another one. Hope that satisfy your original requirements
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ymz |



