回调返回未定义的 chrome.storage.sync.get [英] Callback returns undefined with chrome.storage.sync.get

查看:31
本文介绍了回调返回未定义的 chrome.storage.sync.get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a Chrome extension and I wrote this code.

var Options = function(){};

Options.prototype = {

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

    setMode: function(){
        chrome.storage.sync.set({"value": "test"}, function(e) {         
        })
    }
}

var options = new Options();
options.setMode();
console.log(options.getMode()); // it prints 'undefined'.

我希望它打印

Object {value: "set up"}

当我调用 options.getMode(),但它打印 undefined.

when I call options.getMode(), but it prints undefined.

有人知道如何解决这个问题吗?

Does anyone know how to fix this problem?

推荐答案

chrome.storage API 是异步 - 它不直接返回它,而是将它作为参数传递给回调函数.函数调用本身总是返回 undefined.

The chrome.storage API is asynchronous - it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined.

这通常用于允许其他方法运行而不必等到某事响应或完成 - 一个例子是 setTimeout(唯一的区别是它返回一个计时器值,而不是 未定义).

This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout (only difference is that it returns a timer value, not undefined).

举个例子:

setTimeout(function () { alert(1); }, 10000);
alert(0);

因为 setTimeout 是异步的,它不会停止所有代码直到整个函数完成,而是最初返回,只有在稍后完成时才调用函数 - 这就是为什么 0 在 1 之前出现.

Because setTimeout is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1.

因此,您不能简单地执行以下操作:

For this reason, you cannot simply do something like:

// "foo" will always be undefined
var foo = asyncBar(function (e) { return e; }); 

一般来说,你应该把你想做的事情放在你的回调中(异步函数完成时调用的函数).这是编写异步代码的一种相当常见的方式:

Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way of writing asynchronous code:

function getValue(callback) {
  chrome.storage.sync.get("value", callback);
}

您可以将整个代码部分放在回调中 - 没有什么可以阻止您这样做.因此,不要执行以下操作:

You could place an entire portion of your code inside the callback - there's nothing stopping you from doing so. So instead of doing the following:

console.log(getValue()); // typical synchronous method of doing something

这可能是一个更好的主意:

This would probably be a better idea:

// how it would be done in asynchronous code
getValue(function (value) {
  console.log(value);
}); 

这篇关于回调返回未定义的 chrome.storage.sync.get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆