6

I am having a problem because chrome api functions are async and I cant get its return value. Consider the following code. I am using angularjs

    $scope.storageGet = function(param) {
        var returnData; 

        chrome.storage.local.get(param.storageName, function(data) {
            returnData = data;
        });

        return returnData;
    };

And when I tried to call it like this:

    console.log($scope.storageGet({'storageName': 'users'}));

It prints 'undefined' in the console. What I want to see is the obect of users stored in chrome storage. Well, I'm sure that I have data in chrome storage.

2 Answers 2

7

You cannot return data that is generated by an async function such as chrome.storage.local.get, because more likely your function will finish executing before the async function executes. This is why your function returns undefined, which is the default value of returnData.

A good alternative will be to make your function async as well by using a callback function.

$scope.storageGet = function(param, callback) {
    chrome.storage.local.get(param.storageName, function(data) {
        callback(data);
    });
};

Now you can call your function this way:

$scope.storageGet(param, function(returnData) {
    // do something with returnData
});
Sign up to request clarification or add additional context in comments.

Comments

6

Another way is to use a promise. In this case it might not matter but if you have a a lot of nested callbacks then a promise is better.

$scope.storageGet = function(param) {
    var deferred = $q.defer();

    chrome.storage.local.get(param.storageName, function(data) {
        deferred.resolve(data);
    });

    return deferred.promise;
};

And then you call it like this.

$scope.storageGet(param).then(function (data) {

});

1 Comment

ah. Your solution using promise looks good and easy to undestand because its short hahah. I'll try it later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.