问题描述
由于Chrome API函数的异步和我不能得到它的返回值我有一个问题。请看下面的code。的我使用angularjs 的
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'}));
它打印在控制台未定义。我想看到的是存储在存储铬用户的obect。嗯,我敢肯定,我在镀铬的存储数据。
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.
推荐答案
另一种方法是使用一个承诺。在这种情况下,它可能没有关系,但如果你有很多嵌套的回调,那么一个承诺是更好的。
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) {
});
这篇关于JavaScript的 - 让一个函数内部异步函数的返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!