返回函数之外的对象

时间:2015-04-26 20:21:10

标签: javascript angularjs firebase promise angular-promise

我正在尝试在函数外部返回一个对象。我正在使用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

有没有办法解决这个问题。任何帮助表示赞赏。提前谢谢!

1 个答案:

答案 0 :(得分: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;
}