创建Promise对象

1/28/2023

# Promise的状态

Promise对象代表一个异步操作,有三种状态:

  • Pending(进行中)
  • Resolved(已完成,又称Fulfilled)
  • Rejected(已失败)。

# Promise的状态转换

Promise对象的状态改变,只有两种可能:从Pending变为Resolved和从Pending变为Rejected。

# Promise的then()方法

Promise实例具有then()方法,也就是说,then()方法是定义在原型对象Promise.prototype上的。它的作用是为Promise实例添加状态改变时的回调函数。

then()方法的第一个参数是Resolved状态的回调函数,第二个参数(可选)是Rejected状态的回调函数。

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

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});
1
2
3
4
5

# Promise的catch()方法

Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。

p.then((val) => console.log("fulfilled:", val))
 .catch((err) => console.log("rejected:", err))
 .then(() => console.log("always executed"));
1
2
3

# Promise的finally()方法

Promise.prototype.finally()方法用于指定不管Promise对象最后状态如何,都会执行的操作。它与done()方法的最大区别,它接受一个普通的回调函数作为参数,该函数不管怎样都必须执行。

promise
  .then(result => {···})
  .catch(error => {···})
  .finally(() => {···});
1
2
3
4
编辑时间: 4/12/2023, 5:05:20 PM