在自定义事件详细信息中传递承诺
我正在尝试通过自定义事件的 detail
属性传递 Promise 对象。 自定义事件在不共享相同全局上下文的两个脚本之间传递 - 一个是扩展的内容脚本,另一个是主网站脚本。
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);
});
然后我尝试调用它(从 scriptB
或从第三个不相关的脚本,在 scriptA 之后
和 scriptB
已加载):
document.dispatchEvent(new CustomEvent('eventA'));
当我在分派事件之前打印 scriptA
中的 detail
对象时,它正确显示了 Promise 对象,但它没有到达scriptB
根本没有 - detail
属性以 null
形式到达。
我在这里错过了什么吗?
当我创建一个沙箱来复制它时,它工作正常。
然而,在我的实际代码中,事实并非如此。以下是 Chrome 调试器的屏幕截图:
如果我不在分派的detail
中包含response
(这是一个Promise
对象),那么一切正确到达。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,感谢沙箱 - 它确实加快了速度,并明确了您当前面临的
问题,
我认为问题就在
这里,您附加了调用承诺..为什么不只分配委托?
这行的含义是:将引用分配给我的承诺,但儿子(尚未)调用它。这似乎是你的初衷,因为你后来使用了这段代码
,据我的理解,这应该是
......你不能在一个代码块中调用一个承诺并在另一个代码块中等待结果。希望能满足您最初的要求
First, thanks for the sandbox - it truly speeds things up and made it clear what you are currently facing
To the point
I think that the problem is here
Here you are attach the invokes promise.. why not assign the delegation only?
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
which supposed to be
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