JavaScript的 - 让一个函数内部异步函数的返回数据 [英] javascript - getting the return data of a async function inside a function

查看:147
本文介绍了JavaScript的 - 让一个函数内部异步函数的返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于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的 - 让一个函数内部异步函数的返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆