2016-02-23 88 views
-1

我已經閱讀了How do I return the response from an asynchronous call?這個問題的答案但是我不確定我是否理解,我認爲我的問題有點不同。我改變我的服務是這樣的:如何在angularjs服務中返回異步調用的響應?

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

在我的控制器I存儲變量userCommonService的回報:

var user = CommonService.getUsername(); 
console.log(user); 

的問題是,控制檯仍返回「未定義」 。我試圖根據這些建議更改代碼,但它沒有運行。我該怎麼辦?

在此先感謝

+1

你有所有這些回調,試圖完成不可能的事情。 –

+2

使'getData'和'getUsername'返回一個承諾,而不是回調。 – Bergi

+0

@Bergi我很無知,你可以在代碼中更明確嗎? – Radames

回答

1

異步/等待

我們需要提供一種方式來等待您的請求作出迴應。我們可以使用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; 
     } 
    }; 
}]) 
+0

你不需要聲明'getData'爲'async' - 它已經明確地返回一個新的Promise - 但是你需要在使用'await'的'getUsername'函數中這樣做,以便它返回一個promise好。 – Bergi

+0

當前,如果不首先聲明包含函數作爲異步函數,我們不能使用await。這可能會在即將到來的ECMA更新中發生變化,但在此之前,我們需要等待異步。 也可以將getUsername方法縮短爲 'getUsername:function(){ return await getData(); }' – Rex

+0

是的,正好。而你的代碼不遵循這些規則 - 包含'await'的函數沒有聲明'async' – Bergi