Javascript - getting async function return data inside function

I have a problem because chrome api functions are async and I cannot 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 him like this:

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

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

+5
source share
2 answers

Another way is to use a promise. In this case, it may not matter, but if you have many nested callbacks, then the promise will be 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 that.

 $scope.storageGet(param).then(function (data) { }); 
+6
source

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

A good alternative would be to make your function asynchronously 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 as follows:

 $scope.storageGet(param, function(returnData) { // do something with returnData }); 
+6
source

Source: https://habr.com/ru/post/1200296/


All Articles