0

I have an external page that sends a message to my Chrome Extension and the background script gets it and respond to it. However I want to first process the function getID() and only then send the response (with the ID) back to the external page. I already tried to: set a $.when() and a setTimeout to wait for getID. But nothing works, and the response is always "undefined"...

Is there anyway to wait for the function to execute and only then send the ID back to the external page?!

External page (send Message)

var extID = "pncieomfimcmcbnbnogelnipdnkejmdf";

chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true}, function(response) {
        console.log(response);
});

Background script

var id;

function getID(){
    $.get("url1", function( data1 ) {
        //process data1 and use part of data1 on next get       
        $.get("url2", function( data2 ) {
            //process data2 and use part of data2 on next get
            $.get("url3", function( data3 ) {
                //process data3 and return
                return id;
            });
        });
    });
}

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        getID();
        sendResponse({user: id});       
});
zppinto
  • 287
  • 7
  • 20

1 Answers1

2

You cannot return something from asynchronous functions. Please read that question before proceeding further.

You will need to call sendResponse(id) from inside the last callback. Additionally, you need to inform Chrome that you will be doing that asynchronously by returning true from the handler.

function getID(callback){
    $.get("url1", function( data1 ) {
        //process data1 and use part of data1 on next get       
        $.get("url2", function( data2 ) {
            //process data2 and use part of data2 on next get
            $.get("url3", function( data3 ) {
                //process data3 and pass the result to callback
                callback(id);
            });
        });
    });
}

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
    getID(function(id) {
        // Will be called asynchronously from getID()
        sendResponse({user: id});
    });
    return true; // Tell Chrome we need sendResponse asynchronously
});
Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • `id` would still be `undefined`? – guest271314 Jun 29 '16 at 14:12
  • `id` will not be stored in any global variable, it's only passed to the callback. You can assign it to something, but because everything is asynchronous you need to be careful _when_ you use it. I recommend [reading something on JS asynchronicity](https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch1.md) if that's something you don't understand well yet. – Xan Jun 29 '16 at 14:13