我正在开发一个 chrome 插件,需要将消息从“应用程序页面”发送到“内容脚本”,然后从循环内部获取返回消息。但由于循环在开始下一次迭代之前不会等待 sendMessage 返回值,因此它会搞砸返回值。以下是代码示例:
for (i=0; i<data[i2].data.length; i++)
{
console.log("SENDING: i=" + i + "; i2=" + i2);
// Send message to content script with the query value
chrome.tabs.sendMessage(tabid, {x: 'val-x', y: data[i2].data[i].val-y}, function(response) {
console.log("RECEIVING: i=" + i + "; i2=" + i2);
console.log("RECEIVING: val1=" + response.value1+ "; val2=" + response.value2);
// ANOTHER FUNCTION CALL
dothis(response.value1, response.value2, response.value3);
});
我该怎么做才能使其全部同步工作?
以下是对内容脚本所做操作的概述:
function function1(x) {/* some code ... */}
function function2(y) {/* some code ... */}
// EventListener to listen to messages sent from app
chrome.runtime.onMessage.addListener(
function(sent, sender, sendResponse) {
// some code here //
val1 = function1(sent.x);
val2 = function2(sent.y);
}
sendResponse({value1: val1, value2: val2});
});
因此,在loop1中这些函数被调用。然后,他们在有机会返回值之前再次通过loop2调用。
最佳答案
一种选择是使您的函数(响应)
递归。当它运行时,再次调用相同的方法。传入一些“循环”变量,然后在开始时进行 if 检查。
function AnotherGoRound(i,data) {
if (i<data[i2].data.length) {
console.log("SENDING: i=" + i + "; i2=" + i2);
// Send message to content script with the query value
chrome.tabs.sendMessage(tabid, {x: 'val-x', y: data[i2].data[i].val-y}, function(response) {
console.log("RECEIVING: i=" + i + "; i2=" + i2);
console.log("RECEIVING: val1=" + response.value1+ "; val2=" + response.value2);
// ANOTHER FUNCTION CALL
dothis(response.value1, response.value2, response.value3);
AnotherGoRound(i + 1, data);
});
}
}
AnotherGoRound(0, data);
关于javascript - 如何让循环中的函数同步运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30983400/