Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google chrome extension Chrome扩展sendRequest并返回响应_Google Chrome Extension_Local Storage - Fatal编程技术网

Google chrome extension Chrome扩展sendRequest并返回响应

Google chrome extension Chrome扩展sendRequest并返回响应,google-chrome-extension,local-storage,Google Chrome Extension,Local Storage,我正在开发一个chrome扩展。我有一个函数,它从本地存储中检索一个JOSN字符串并返回它 它不能正常工作,这是我的代码 function getstore() { var all = {}; chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) { all = JSON.parse(response.data); console.log(all

我正在开发一个chrome扩展。我有一个函数,它从本地存储中检索一个JOSN字符串并返回它

它不能正常工作,这是我的代码

function getstore()
{
    var all = {};
    chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) {
        all = JSON.parse(response.data);
        console.log(all); //it prints the JSON properly
        return all; //
    });
}
但每当我像这样调用该函数时:

var old_a = getstore();// old_a should hold the JSON returned by getstore()
console.log(old_a);

但是这里“old_a”的值变得不确定。

实际上,您没有从方法
getstore()
返回任何内容

sendRequest方法有一个回调函数,它在异步函数完成时调用该函数。方法签名如下所示:

chrome.extension.sendRequest(options, responseCallback)
所以responseCallback是您添加为最后一个参数的函数

function(response) {
    all = JSON.parse(response.data);
    console.log(all); //it prints the JSON properly

    return all; // No sense in returning from a callback method, it will do nothing and will never be catched anywhere.
}
因此,您要做的是:

function getstore()
{
    chrome.extension.sendRequest({method: "getlist", key: "" }, function(response) {
        var old_a = JSON.parse(response.data);

        // Use the json object here.
        console.log(old_a); 
    });
}

非常感谢!