Promise.prototype.then()

Promise 实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。
then方法的第一个参数是resolved状态的回调函数,
第二个参数(可选)是rejected状态的回调函数。

 then链式写法 

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});
上面的代码使用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); }
);
第一个then方法指定的回调函数,返回的是另一个Promise对象。
这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。
如果变为resolved,就调用第一个回调函数,
如果状态变为rejected,就调用第二个回调函数。
getJSON("/post/1.json").then(
  post => getJSON(post.commentURL)
).then(
  comments => console.log("resolved: ", comments),
  err => console.log("rejected: ", err)
);

  

 

猜你喜欢

转载自www.cnblogs.com/blogZhao/p/12565780.html