gpt4 book ai didi

javascript - 在回调中调用异步函数

转载 作者:行者123 更新时间:2023-11-28 11:56:03 25 4
gpt4 key购买 nike

我的background.js中有这段代码:

chrome.extension.onMessage.addListener( function(request,sender,sendResponse){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var requests = getTabRequests(tabs[0].id);
//getTabRequests gets all the information i stored about a tab
sendResponse( {requests: requests});
});
});

我想要它做的是响应 popup.js。 chrome.tabs.query这对我来说是不可能的。我意识到这是一个异步函数,但是如何修复它呢?或者是不发送响应的唯一可能性,而只是在不同方向发送另一条消息(这意味着我无法使用 mu popup.js 中的回调函数)

最佳答案

阅读 chrome.runtime.onMessage 的文档:

function sendResponse
Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var requests = getTabRequests(tabs[0].id);
//getTabRequests gets all the information i stored about a tab
sendResponse({requests: requests});
});
<b>return true; // <-- Required if you want to use sendResponse asynchronously!</b>
});

(chrome.extension.onMessage 已弃用,请使用 chrome.runtime.onMessage 代替,但前者是后者的别名。)

关于javascript - 在回调中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22696142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com