「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」。
前几篇分别介绍了Promise
的基本用法、开发中常用的封装方法等,那么今天继续说Promise
中的then
方法。
一、 Promise
的then
方法
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)
);
关于Promise
的then
方法就更新完毕了,下一篇是Promise
的catch
方法。