如何在异步 forEach 循环之后添加回调函数?
这是一些更好的上下文:
$scope.getAlbums = function(user, callback) {
$scope.albumsList.forEach(function (obj, i) {
$scope.getAlbum(user, obj.id, function(value){
$scope.albums.push(value);
});
});
// callback(); ???
};
$scope.getAlbums('guy123', function(){
// forEach loop is all done!
console.log($scope.albums)
});
控制器:
.controller('Filters', ['$scope','Imgur', function($scope, Imgur) {
$scope.getAlbum = function(user, id, callback) {
Imgur.album.get({user:user, id:id},
function(value) {
return callback(value.data);
}
);
}
$scope.getAlbums = function(user, callback) {
// Callback function at end of this forEach loop?
// Request is async...
$scope.albumsList.forEach(function (obj, i) {
$scope.getAlbum(user, obj.id, function(value){
$scope.albums.push(value);
});
});
};
)]};
服务:
.factory('Imgur', function($resource) {
return {
album : $resource('https://api.imgur.com/3/account/:user/album/:id')
}
});