如何同步循环运行中的函数?

How to make function in loop run synchronously?

我正在开发 chrome 插件,需要从 'app page' 发送消息到 'content script',然后从循环内部获取 return 消息。但是由于循环在开始下一次迭代之前不等待 sendMessage 达到 return 一个值,所以它搞砸了 return 值。这是代码的示例:

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 中调用了这些函数。然后,他们在有机会 return 返回值之前通过 loop2 再次调用。

一种选择是使您的 function(response) 递归。当它运行时,再次调用相同的方法。传入你的一些 "looping" 变量,然后在开始时做一个 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);