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

How to make function in loop run synchronously?

本文关键字:函数 同步 运行 何使 循环      更新时间:2023-09-26

我正在开发一个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再次调用。

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