这个javascript中发生了什么,我该如何解决?

时间:2011-08-24 00:49:05

标签: javascript google-chrome-extension

我有一个chrome扩展程序,其中包含一个可以执行的javascript文件。 javascript文件调用background.html:

action.js

var action = "";
chrome.extension.sendRequest({method: "getLocalStorage", key: "action"},
  function(response) {
     alert(response.data);
     action = response.data;
 });
alert('action:'+action);

并在 background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
  sendResponse({data: localStorage[request.key]});
else
  sendResponse({});

我得到的行为是一个警告框,上面写着“action:”,然后是一个警告框,上面写着“video”,这是正确的行动价值。

为什么这些警告框显示乱序,为什么变量action没有获得response.data值?是否与sendRequest方法的延迟有关?如何使脚本等待,以便我可以获得值? (我将需要多次执行此请求 - 我需要请求4个值)

1 个答案:

答案 0 :(得分:3)

我认为sendRequest是一种异步方法(很像Ajax调用)。脚本不会停止并等待响应。

唯一的解决方案是调用其他需要回复内部回调的函数。