考虑这段代码:
WordPress.getMediaById(res.data.featured_media)
.then(function (res) {
post.featuredMedia = res.data.source_url;
WordPress.getUserById(post.authorId)
.then(function (res) {
post.authorName = res.data.name;
$scope.post = {
title: post.title,
introAsHtml: post.introAsHtml,
authorName: post.authorName,
contentAsHtml: post.contentAsHtml,
featured_media: post.featuredMedia
};
});
});
有什么办法可以让它在嵌套方面更加高效吗?将来我想向其中添加更多 promise 的功能,但我不确定这是否是正确的方式,否则,它与回调有何不同......
问候。
最佳答案
除非第二个异步请求不依赖于第一个调用的结果,否则我绝对不会嵌套 promise 。
在 Angular 的 $q
的帮助下,你可以这样:
$q.all([
WordPress.getMediaById(mediaId),
WordPress.getUserById(userId)])
.then(response => {
post.featuredMedia = response[0].data.source_url;
post.authorName = response[1].data.name;
$scope.post = {
title: post.title,
introAsHtml: post.introAsHtml,
authorName: post.authorName,
contentAsHtml: post.contentAsHtml,
featured_media: post.featuredMedia
};
});
关于angularjs - JS Promises - 使这个 promise 嵌套更有效的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568019/