我的回调函数没有像我预期的那样返回“undefined”

时间:2013-09-09 09:54:12

标签: javascript jquery google-chrome-extension

我正在构建Chrome扩展程序并编写了此代码。

我希望它打印'Object {value:“set up”}'wnen我调用options.getMode()。 但是,它打印'undefined'。

var Options = function(){};

Options.prototype = {

    getMode: function(){

            chrome.storage.sync.get('value', function(e){         
               console.log(e); // it prints 'Object {value: "set up"}' in console.
               return e;
             })
    }
}


var options = new Options();

console.log(options.getMode()); // it prints "undefined" in console.

chrome.storage.sync.get()的第二个参数是回调函数。 我想知道回调函数是否不返回对象(e)。

当我调用options.getMode()时,我希望它打印出'undefined'。

这段代码出了什么问题?

请帮帮我!

我认为我误解了一些非常基本的东西。

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个,

 return chrome.storage.sync.get('value', function(e){         
      console.log(e); // it prints 'Object {value: "set up"}' in console.
      return e;
 });

完整代码

var Options = function(){};
Options.prototype = {
    getMode: function(){
               return chrome.storage.sync.get('value', function(e){         
                 console.log(e);
                 return e;
               });
    }
}

var options = new Options();
console.log(options.getMode());

答案 1 :(得分:0)

Storage.get是异步的。

所以你的代码应该是这样的:

var Options = function(){};

Options.prototype = {

    getMode: function(callback){

            chrome.storage.sync.get('value', function(e){
               //this function is executed somewhere in the future        
               callback(e);
             })
    }
}


var options = new Options();
options.getMode(function(mode){
    //do some stuff with mode here   
    console.log("Mode is", mode);
});