Am working on a chrome plugin, and need to sendMessage from an 'app page' to a 'content script' and then get the return messages, from inside a loop. But since the loop doesn't wait for the sendMessage to return a value before starting on the next iteration, it is screwing up the return values. Here is a sample of what the code looks like:
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);
});
What can I do to make it all work synchronously?
Here is an overview of what am doing on the content-script:
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});
});
So, in loop1 these functions get called. Then, they called again by loop2 before they have a chance to return the values back.