What is going on in this javascript, and how can I fix it?
I have a chrome extension, with a javascript file that gets executed. The javascript file makes this call to background.html:
action.js
var action = "";
chrome.extension.sendRequest({method: "getLocalStorage", key: "action"},
function(response) {
alert(response.data);
action = response.data;
});
alert('action:'+action);
and in background.html:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({});
The behavior th开发者_如何转开发at i get is an alert box saying "action:
" and then an alert box saying "video
" which is the correct value for action.
Why are these alert boxes showing out of order, and why isn't the variable action
getting the response.data
value? Does it have to do with a delay from the sendRequest
method? How can I make the script wait, so that I can get the value? (I'm going to need to do this request multiple times - I have 4 values that I need to request)
I assume sendRequest
is an asynchronous method (much like an Ajax call). The script does not halt and wait for the response.
The only solution is to call the other functions which need the response inside the callback.
精彩评论