javascript - getting the return data of a async function inside a function

痴心易碎 提交于 2019-11-30 20:28:56

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) {

});

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
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!