Promise.prototype.then()使用技巧

在多个含有异步操作的函数之间有依赖关系时,为清晰的展示依赖关系,建议使用如下方法。

当then方法返回一个新的Promise实例(注意,不是原来那个Promise实例)。可以采用链式写法,即then方法后面再调用另一个then方法

getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function (comments) {
  console.log("resolved: ", comments);
}, function (err){
  console.log("rejected: ", err);
});

如果采用箭头函数,上面的代码可以写得更简洁。

getJSON("/post/1.json").then(
  post => getJSON(post.commentURL)
).then(
  comments => console.log("resolved: ", comments),
  err => console.log("rejected: ", err)
);
原文地址:https://www.cnblogs.com/hjsblogs/p/11983843.html