角度承诺没有正确解决

时间:2016-03-09 22:50:25

标签: javascript angularjs q angular-promise

我正在努力获得Firebase查询后解析的承诺。基本上我想从表中获取所有指定的键,然后循环遍历另一个表,以获得我想要的艺术作品。

artistFactory.js

'use strict';

angular.module('artvoicesApp')
  .factory('Artist', function(localStorageService, FIREBASE_URL, $q) {

    var artistData = {};
    var userKey = localStorageService.get('userKey');
    var accountKey = localStorageService.get('accountKey');
    var artistRef = FIREBASE_URL.child('v2/artist');
    var accountRef = FIREBASE_URL.child('v2/account/' + accountKey);
    var userRef = FIREBASE_URL.child('v2/user/' + userKey);

    artistData.addArtist = function(artistName) {
      var artist = artistRef.push();
      accountRef.child('artists/' + artist.key()).set(true);
      userRef.child('artists/' + artist.key()).set(true);
      artist.set({name: artistName});
      artist.child('users/' + userKey).set(true);
      artist.child('accounts/' + accountKey).set(true);
    };

    artistData.getArtistKeys = function() {
      var artistKeys = [];
      var defer = $q.defer();
      accountRef.child('artists').once('value', function(snapshot) {
        snapshot.forEach(function(childSnapShot) {
          artistKeys.push(childSnapShot.key());
        });
        defer.resolve(artistKeys);
      });
      return defer.promise;
    };

    artistData.getArtists = function(artistKeys) {
      var artistObj = {};
      var artistRef = FIREBASE_URL.child('v2/artist');
      var defer = $q.defer();

      artistKeys.forEach(function(artist) {
        artistRef.child(artist).once('value', function(snapshot) {
          artistObj[artist] = snapshot.val();
        });
        defer.resolve(artistObj);
      });
      return defer.promise;
    };

    return artistData;
  });

artwork.controller.js

Artist.getArtistKeys().then(function(artistKeys) {
  Artist.getArtists(artistKeys).then(function(artists) {
      vm.artists = artists;
      console.log(vm.artists);
  });
});

如果我将vm.artwork设置为超时,则会返回相应的数据。

1 个答案:

答案 0 :(得分:1)

这是你的问题:

  artistKeys.forEach(function(artist) {
    artistRef.child(artist).once('value', function(snapshot) {
      artistObj[artist] = snapshot.val(); // <<== This is called second, at an unspecified time in the future
    });
    defer.resolve(artistObj);  // <<== This is called first
  });

artistObj的所有作业都将在之后发出defer.resolve(artistObj)。这就是为什么它在添加超时后似乎有效。

您需要将您的艺术家集合映射到承诺集合,然后等待所有这些承诺解决。

artistData.getArtistKeys = function(artistKeys) {
  var artistObj = {};
  var artistRef = FIREBASE_URL.child('v2/artist');
  var allPromises = artistKeys.map(function(artist) {
    var childDefer = $q.defer();
    artistRef.child(artist).once('value', function(snapshot) {
      artistObj[artist] = snapshot.val();
      childDefer.resolve();
    });
    return childDefer.promise();
  });
  // allPromises is now an array of promises
  var defer = $q.defer();
  $q.all(allPromises).then(function() {
    defer.resolve(artistObj);
  });
  return defer.promise();
}