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

时间:2015-06-22 15:03:50

标签: javascript jquery loops google-chrome-extension synchronization

我正在使用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调用,然后才有机会返回值。

1 个答案:

答案 0 :(得分:1)

一种选择是让你的function(response)递归。运行时,再次调用相同的方法。通过你的一些&#34;循环&#34;变量,只需在开头检查。

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);