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

时间:2016-04-12 08:46:46

标签: angularjs node.js ionic-framework promise angular-promise

考虑这段代码:

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

有没有办法让它在嵌套方面更有效率?将来我会希望在其中添加更多承诺的功能,我不确定它是否正确,否则,它与回调有什么不同......

问候。

2 个答案:

答案 0 :(得分:4)

您可以像这样减少嵌套:

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博客

答案 1 :(得分:4)

除非第二次异步请求不依赖于第一次调用的结果,否则我绝对不会嵌套承诺。

在角度$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
  };
});