关于Promise那些事系列(4)

107 阅读2分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」。

前几篇分别介绍了Promise的基本用法、开发中常用的封装方法等,那么今天继续说Promise中的then方法。

一、 Promisethen方法

1.then

Promise实例具有then方法,实际上then方法是定义在原型对象Promise.prototype上的。

then方法的作用是Promise实例添加状态改变时的回调函数。之前几篇说过then方法的第一个参数是resolved状态的回调函数,第二个参数rejected状态的回调函数,这两个参数都是可选的。

then方法返回的是一个新的Promise实例。因此Promise也可以采用链式写法,也就是then方法后面再次调用一个then方法。

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...一些代码
});

这段代码中,使用了两次then方法。第一个回调函数完成之后,会将返回的结果作为参数,传入第二个回调函数。

采用链式结构的写法的话,可以指定一组按照次序调用的回调函数。这个时候,前一个回调函数有可能会返回的还是一个Promise对象,这个时候,后一个回调函数就会等待前一个Promise对象的状态发生改变后,才会执行。

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

上面这段代码中,第一个then方法指定的回调函数,返回的是另一个Promise对象。这个时候,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化,才会执行。如果变为resolved,就调用第一个回调函数,如果状态变为rejected,就调用第二个回调函数。

我们也可以采用箭头函数的方式简化上面的代码

HttpX("/post/1.json").then(
  post => getJSON(post.commentURL)
).then(
  comments => console.log("resolved: ", comments),
  err => console.log("rejected: ", err)
);

关于Promisethen方法就更新完毕了,下一篇是Promisecatch方法。

image.png