JS Promises - 使这个承诺嵌套更有效的方法?

JS Promises - way to make this promise nesting more efficient?

考虑这段代码:

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
      };
    });
});

在嵌套方面有什么办法可以提高效率吗?将来我会想在其中添加更多承诺的功能,但我不确定这是不是正确的方法,否则,它与回调有何不同...

此致。

你可以这样减少嵌套:

WordPress.getMediaById(res.data.featured_media)
.then(function (res) {
    //res.data is media
  post.featuredMedia = res.data.source_url;

  return WordPress.getUserById(post.authorId);
}).then(function (res) {
    //res.data is user
  post.authorName = res.data.name;

  $scope.post = {
    title: post.title,
    introAsHtml: post.introAsHtml,
    authorName: post.authorName,
    contentAsHtml: post.contentAsHtml,
    featured_media: post.featuredMedia
  };
});

有关承诺的更多信息和清晰解释,请阅读 this Nolan Lawson 的博客

除非第二个异步请求不依赖于第一个调用的结果,否则我绝对不会嵌套 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
  };
});