简体   繁体   English

javascript函数运行乱序

[英]javascript function running out of order

In a Chrome Extension, I am trying to get saved information from the option page and use it in a content script. 在Chrome扩展程序中,我尝试从选项页面获取已保存的信息,并在内容脚本中使用它。 I am passing a message to the background script to get it. 我正在向后台脚本传递消息以获取它。 I have surrounded the sendMessage in the content script in a temporary function(I think that's what it's called) so that I could store the color outside of it. 我已经在一个临时函数中包含了内容脚本中的sendMessage(我认为这就是它的名称),以便我可以将颜色存储在它之外。 Unfortunatly it leads to things running about out of order. 不幸的是,它会导致事情无序发生。 The output from the code below is: 以下代码的输出是:

3red 3red

1red 1red

2blue 2blue

I assume this has something to deal with the fact that I have created a temporary function. 我认为这有一些事情要处理我创建了一个临时函数的事实。

Content_script.js: Content_script.js:

    (function(){
        chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"},
             function(response) {
                 console.log("1"+color);
                 color = response.data;
                 console.log("2"+color);
             }
        )
     })(color);

console.log("3"+color);
a.style.backgroundColor = color;

Background.js: Background.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

The problem here is that the chrome runtime is running asynchronously. 这里的问题是chrome运行时异步运行。 So when you execute that first function, it won't log those 1 and 2 messages until after the response is sent. 因此,当您执行第一个函数时,它将不会记录这些1和2消息,直到发送响应为止。 It registers the callback and proceeds with the rest of the script. 它注册回调并继续执行脚本的其余部分。 Since it takes a little bit of time for the runtime to respond, even though it may be fast, it won't receive a message back until after it's already logged 3 to the console. 由于运行时需要一点时间来响应,即使它可能很快,它也不会收到消息,直到它已经记录3到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM