Reputation: 2488
I'm developng a chrome extension. I have a function which retrieve a JOSN string from Local Storage and return it.
It not working properly, Here is my code.
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; //
});
}
But whenever I'm calling that function like this :
var old_a = getstore();// old_a should hold the JSON returned by getstore()
console.log(old_a);
But here the value of "old_a" is becoming undefined.
Upvotes: 0
Views: 570
Reputation: 11945
Actually you are not returning anything from the method getstore()
.
The sendRequest method has a callback function that it calls when the asynchronous function is finished. The method signature looks like this:
chrome.extension.sendRequest(options, responseCallback)
So the responseCallback is the function you added as the last parameter.
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.
}
So what you would want to do is:
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);
});
}
Upvotes: 1