简体   繁体   English

返回值包装在javascript中的匿名函数周围

[英]Return value wrapped around anonymous function in javascript

Could someone explain to me what's wrong with checkX() 's scope? 有人可以向我解释checkX()的范围有什么问题吗? What I'm suspecting that's wrong is the anonymous function somehow blocks it but I'm not sure how to bypass that. 我怀疑这是错误的,匿名函数以某种方式阻止了它,但我不确定如何绕过它。

storage = chrome.storage;

function checkX(){
    var x = false;

    storage.sync.get(function(data){
        if(data.x == true){
                x = true;
                console.log(x); // << x : true
        }
    });

            console.log(x); // << x : false
    return x;
}

console.log result order: console.log结果顺序:

x : false
x : true

2 things that might -and probably will- throw you: 有两件事可能会(甚至可能会)抛出您:

  1. JavaScript is case-Sensitive JavaScript区分大小写
  2. the get method, as used by you is asynchronous , your IIFE returns prior to the passed callback function is being executed, so it'll return the value of x before the callback changes it anyhow. 您所使用的get方法是异步的 ,您的IIFE在执行传递的回调函数之前返回,因此它将在回调更改它之前返回x的值。

Edit: 编辑:
The get method is just a getter, fair enough, however there is a major difference between chrome.storage.sync.get , which gets the data using google sync, and chrome.storage.local.get , which is (almost) the same thing as using the localStorage object, with the added benefits of events. get方法只是一个吸气剂,足够公平,但是chrome.storage.sync.getchrome.storage.local.get之间存在主要区别, chrome.storage.sync.get通过google sync获取数据就像使用localStorage对象一样,具有事件的附加好处。 At least, that's what Google's docs are telling me at first glance? 至少,这就是Google文档乍一看告诉我的?

From the comments below: 从下面的评论:
The issue here is how and when JS calls the callback function. 这里的问题是JS如何以及何时调用回调函数。 Even though the getter the OP uses is getting local data, the IIFE has to return first, before JS, being single threaded, can call the callback. 即使OP使用的getter获取本地数据,IIFE也必须先返回,然后单线程JS才能调用回调。 That's why the IIFE returns false . 这就是IIFE返回false的原因。

Javascript is case sensitive. JavaScript区分大小写。 What you are doing is creating a global variable x which is true , while the local variable X remains false . 您正在做的是创建一个为true的全局变量x ,而局部变量X保持为false

storage = chrome.storage;

function checkX(){
    var X = false;

    storage.sync.get(function(data){
        if(data.x == true){
            x = true;  <--- global variable
        }
    });

    return x;
}

Another issue would be if the storage.sync.get runs async from the "checkX", which would mean that first you return x and only later on (after you have returned it) will your function be executed. 另一个问题是,如果storage.sync.get从“ checkX”异步运行,这意味着首先返回x,然后(返回之后)才执行函数。 This will happen for sure if storage.sync.get is an ajax call. 如果storage.sync.get是ajax调用,则将确保发生这种情况。

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

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