2015-04-26 86 views
2

我試圖返回函數之外的對象。我正在使用Angular JS承諾在加載時記錄了availableProviders,該記錄正確記錄到我的控制檯。函數之外的返回對象

function getServiceProviders(serviceId) { 
    var serviceProviders = ref.child('services').child(serviceId).child('providers'); 
    var providers = ref.child('providers'); 

    serviceProviders.on('value', function(snapshot) {  // on services.serviceId.providers 
    var availableProviders = {};       // create empty availableProviders array 

    snapshot.forEach(function(childSnapshot) {    // for each provider in services.serviceId.providers 
     var key = childSnapshot.key();      // grab each provider's key 
     providers.on('value', function(snap) {    // on providers 
     if (snap.hasChild(key)) {       // if providers has a child that matches the var key above 
      var item = snap.child(key);      // store that child in a var called item 
      availableProviders[item.key()] = item.val();  // add item to availableProviders array 
     } 
     }); 
    });             // rinse and repeat 

    var defer = $q.defer(); 
    defer.promise 
     .then(function() { 
     console.log(availableProviders); 
     }) 

    defer.resolve(); 
    }); 

    return availableProviders; 
} 

我想getServiceProviders()函數返回這些availableProviders, but I'm getting this error as availableProviders`不是該函數的定義之外。

ReferenceError: availableProviders is not defined 

有沒有辦法解決這個問題。任何幫助表示讚賞。提前致謝!

回答

3

與JavaScript中的閉包相關的問題,我認爲您需要將var availableProviders = {};移出serviceProviders.on('value', function(snapshot) {函數將解決您的問題。

代碼

function getServiceProviders(serviceId) { 
    var serviceProviders = ref.child('services').child(serviceId).child('providers'); 
    var providers = ref.child('providers'); 
    var availableProviders = {}; // <==made it global 
    serviceProviders.on('value', function(snapshot) { // on services.serviceId.providers 

     snapshot.forEach(function(childSnapshot) { // for each provider in services.serviceId.providers 
      var key = childSnapshot.key(); // grab each provider's key 
      providers.on('value', function(snap) { // on providers 
       if (snap.hasChild(key)) { // if providers has a child that matches the var key above 
        var item = snap.child(key); // store that child in a var called item 
        availableProviders[item.key()] = item.val(); // add item to availableProviders array 
       } 
      }); 
     }); // rinse and repeat 

     var defer = $q.defer(); 
     defer.promise 
      .then(function() { 
       console.log(availableProviders); 
      }) 

     defer.resolve(); 
    }); 

    return availableProviders; 
} 
+1

啊哈!所以它就像在全球定義'availableProviders'一樣簡單? – realph

+1

此外,此時還需要延期嗎? – realph

+1

雅..這很容易..推遲不應該在那裏,因爲它什麼都不做 –