简体   繁体   English

角$ q嵌套承诺

[英]Angular $q nested promise

I have a function that needs to return a list of favorite locations. 我有一个需要返回收藏位置列表的函数。 Something like this 像这样

LocationsFactory.getFavoriteLocations().then(function($favoriteLocations) { }); LocationsFactory.getFavoriteLocations()。then(function($ favoriteLocations){});

The getFavoriteLocations looks something like this getFavoriteLocations看起来像这样

getFavoriteLocations: function() {
                if (favorite_locations.length == 0)
                {
                    var deff = $q.defer();
                    obj.getDeviceId().then(function(device_id) {
                    $http.get('url?token=' + device_id).then(function(response) {
                                 favorite_locations = response.data;
                                 deff.resolve(favorite_locations);
                                 return deff.promise;
                               })
                    })
                } else {
                    return favorite_locations;
                }
            }

The getDeviceId again, it's a function based on promise. 再次使用getDeviceId,这是一个基于promise的函数。

getDeviceId: function() {
  var deff = $q.defer();
  deff.resolve(Keychain.getKey());
  return deff.promise;
}

The error that I got is TypeError: Cannot read property 'then' of undefined. 我得到的错误是TypeError:无法读取未定义的属性'then'。 Please help! 请帮忙!

$q in not necessary here: $q在这里没有必要:

if (favorite_locations.length == 0)
{
    return obj.getDeviceId() // you have to return a promise here
        .then(function(device_id) { 
            return $http.get('url?token=' + device_id) // you will access the response below
        })
        .then(function(response) {
            favorite_locations = response.data;
            return favorite_locations
        });
    })
}

Now it should work. 现在应该可以了。

You can chain promises: 您可以连锁承诺:

        getFavoriteLocations: function () {
            if (favorite_locations.length === 0) {
                return obj.getDeviceId().then(function (device_id) {
                    return $http.get('url?token=' + device_id).then(function (response) {
                         favorite_locations = response.data;
                         return favorite_locations;
                    });
                });
            }

            return $q.resolve(favorite_locations);
        }

And improve this: 并改善此:

getDeviceId: function() {
    return $q.resolve(Keychain.getKey());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM