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

Javascript 如何从angularjs服务内的异步调用返回响应?,javascript,angularjs,asynchronous,Javascript,Angularjs,Asynchronous,我已经阅读了问题的答案,但我不确定我是否理解得很好,我认为我的问题有点不同。我以这种方式更改服务: .service('CommonService',['$firebase', function($firebase){ var username; function onComplete(result){ username = result; }; var getData = function(){ var ref = new Firebase("https://insta

我已经阅读了问题的答案,但我不确定我是否理解得很好,我认为我的问题有点不同。我以这种方式更改服务:

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

var username;

function onComplete(result){
    username = result;
};

var getData = function(){

    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;
            callback(newUsername);

        })
    });
  };

    return{
        getUsername: function(){
            getData(onComplete);
            return username;}
    };
}])
在我的控制器中,我将
user
返回的
CommonService
存储在一个变量中:

var user = CommonService.getUsername();
console.log(user);
问题是控制台仍然返回“未定义”。我试图按照建议更改代码,但它没有运行。我该怎么办

提前谢谢

异步/等待

我们需要提供一种等待您的请求响应的方法。我们可以使用async/await来实现这一点,让我们承诺处理我们正在检索的值的解析

.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;
        }
    };
}])

你有所有这些回调,试图完成不可能的事情。让
getData
getUsername
返回一个承诺,而不是接受回调。@Bergi我太无知了,你能在代码中更明确一些吗?我想知道什么是
callback(newUsername)是。是否在某个地方定义了
callback()
?似乎需要提供“callback”作为
getData()的参数
定义。您不需要将
getData
声明为
async
——它已经显式返回了一个新的承诺——但您需要在使用
wait
getUsername
函数中这样做,以便它也返回一个承诺。目前,如果不首先将包含函数声明为异步函数,则不能使用wait。这可能会在即将到来的ECMA更新中发生变化,但在此之前,我们需要异步等待。您还可以将getUsername方法缩短为
getUsername:function(){return await getData();}
Yes。并且您的代码不遵循这些规则-包含
await
的函数未声明为
async