如何从angularjs服务中的异步调用返回响应?

时间:2016-02-23 18:24:36

标签: javascript angularjs asynchronous

我已经阅读过How do I return the response from an asynchronous call?问题的答案但是我不确定我是否理解它,我认为我的问题有点不同。我以这种方式改变我的服务:

user

在我的控制器中,我在变量CommonService内存储了var user = CommonService.getUsername(); console.log(user); 的返回值:

"ABCDEFGH".reverse.split(/(...)/).reject(&:empty?).map(&:reverse)
# => ["FGH", "CDE", "AB"]

问题是控制台仍然会返回"未定义" 。我试图按照建议更改代码,但它没有运行。我该怎么办?

提前致谢

1 个答案:

答案 0 :(得分:1)

  

Async / Await

我们需要提供一种方法来等待您的请求的响应。我们可以使用async / await来执行此操作,并让Promise来处理我们正在检索的值;

.service('CommonService',['$firebase', function($firebase){

var username;
var getData = function(){     //declare this function as an async

    return new Promise((resolve, reject) => { 

        var ref = new Firebase("https://instafame.firebaseio.com");

        ref.onAuth(function(authData){
            var userid = authData.uid;
            console.log(userid);

            var newref = new Firebase("https://instafame.firebaseio.com/users/" + userid)

            newref.once("value", function(snapshot) { 
                var data = snapshot.val()
                newUsername = data.username;
                !!newUsername 
                    ?
                resolve(newUsername)
                    :
                reject('Error: No username found');
            })

       });
    };
 };

    return{
        getUsername: async function(){
            username = await getData(); //await will pause execution of the code here until getData() returns a value.
            return username;
        }
    };
}])