【发布时间】:2016-04-13 12:47:22
【问题描述】:
我在我的控制器中使用了 Promise,而且大多数时候它运行良好。但有时它只是永远加载,WordPress.getAllCategories() 函数甚至不会被调用。
这是我的控制器: var mod = angular.module('app.controllers.home', []);
mod.controller('HomeCtrl', function ($scope, $q, $sce, $ionicPlatform, WordPress, Loading) {
console.log('HomeCtrl init');
$scope.$on('$ionicView.enter', function () {
Loading.show();
WordPress.getAllCategories()
.then(function (cats) {
console.info(angular.toJson(cats));
console.info('cats ^');
$q.all(cats.data.map(function (cat) {
var d = $q.defer();
console.error(cat.name);
WordPress.getLatestPostOfCategory(cat.id)
.then(function (post) {
console.debug(post.data.title.rendered);
WordPress.getMediaById(post.data.featured_media)
.then(function (media) {
console.log(media.data.source_url);
cat.firstPost = {};
cat.firstPost.id = post.data.id;
cat.firstPost.title = post.data.title.rendered;
cat.firstPost.content = post.data.content.rendered;
if (cat.firstPost.title.length > 50) {
cat.firstPost.title = cat.firstPost.title + '...';
}
if (cat.firstPost.content.length > 70) {
cat.firstPost.content = cat.firstPost.content.substr(0, 60) + '...';
}
cat.firstPost.thumbnail = media.data.source_url;
d.resolve(cat);
}, function (err) {
console.error(angular.toJson(err));
});
});
return d.promise;
})).then(function (cats) {
console.log('Loaded all articles and for main page.');
$scope.homeCategories = cats;
Loading.hide();
});
});
});
});
我的控制器有什么问题吗? 附:我还调试了所有 WordPress 服务功能,它们工作得很好,并提供了所需的数据。
编辑:
有时当它永远加载时,我看到 console.error(cat.name); 调试消息只记录 3 条消息。但还是继续下一个函数……
【问题讨论】:
-
避免使用deferred antipattern,您的所有问题都会迎刃而解! (提示:您将在数组中留下一些永远待定的承诺)
-
@Bergi 你能举个例子吗?我正在尝试几个小时......
-
总是
return一个承诺,来自 每个 异步函数。尤其是then回调。 -
@Bergi 嘿,这样更好吗?我在正确的解决方案上吗? jsfiddle.net/48v4f5nw/1
-
是的,就是这样,我没有发现任何遗漏。它在工作吗?你可能想post it as an answer
标签: angularjs asynchronous ionic-framework promise q