0

I'm currently working on a Chrome Extension.

content_script.js

$(document).ready(function(){
    var IPToken;
    function doSomething() {
        chrome.runtime.sendMessage({method: "getToken"}, function(response) {               
            return response.token;
        });
    }
    IPToken = doSomething();
    console.log(IPToken);

background.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
       if (request.method == "getToken")
      sendResponse({token: localStorage["IPToken"]});// IPToken is just a string
  });

IPToken is always undefined. As I understand it, this is because the function won't wait for a response? If so, how can I make sure the response has returned before setting IPToken = doSomething() ?

EDIT: I need the value of response.token further down in another function. This is why I'm trying to store the value in the var IPToken.

UPDATE:

function onComplete(a){ // When the code completes, do this
    console.log(a);// this works, it returns the true result!!
    return a;
}

function getToken(whenDone){            
    setTimeout(function(){
        chrome.runtime.sendMessage({method: "getToken"}, function(response) {           
            whenDone(response.token);
        });
    },10);
}
var IPToken = getToken(onComplete);
console.log("Token is: "+IPToken);// undefined
ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • 1
    You don't. You do something when the response is received. – Barmar Oct 08 '15 at 01:17
  • @Barmar You duplicate answer doesn't answer my question... All of that is related to Ajax, this has nothing to do with it. Never the less, I've tried something from that page but it's still undefined. See updated post... – ProEvilz Oct 08 '15 at 02:11
  • There's nothing special about AJAX. You use the same techniques for all asynchronous actions. – Barmar Oct 08 '15 at 02:12
  • I've added the code now. Well, if that's the case.. why am I still failing? – ProEvilz Oct 08 '15 at 02:15
  • It makes no sense to use `return a` in an asynchronous callback function. Where do you think you're returning it to? The callback function is called asynchronously, when the response comes. – Barmar Oct 08 '15 at 02:19
  • Put `IPToken = response.token;` in the callback function. – Barmar Oct 08 '15 at 02:21
  • I don't understand, I'm just trying to store the response.token globally – ProEvilz Oct 08 '15 at 02:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/91681/discussion-between-ashley-brown-and-barmar). – ProEvilz Oct 08 '15 at 02:32
  • You can store it globally. But you can't access it immediately. Javascript is single-threaded, so the async function won't execute until you return to the main event loop. You can access the token later, once the async call has finished, for instance in another event handler. – Barmar Oct 08 '15 at 06:56

0 Answers0