Promise基本概念、语法

一、Promise对象

(1)三种状态
  • Pending:进行中
  • fulfull:已成功
  • rejected:已失败

注:只有异步操作的结果可以决定当前状态

(2)状态变化
  • pending 到 fulfull
  • pending 到 rejected

注:状态一旦改变,就不会再变,并且任何时候都可以得到这个结果

二、基本用法

1、Promise构造函数:Promise(excutor){}

Ø excutor函数:同步执行(resolve,reject)\=>{}

Ø resolve函数:内部定义成功时调用的函数value=>{}

Ø reject函数:内部定义失败时调用的函数reason=>{}

 excutor会在Promise内部立即同步回调,异步操作在执行器中执行

2、Promise.prototype.then方法:(onResolved,onRejected)=>{}

Ø onResolved函数:成功的回调函数(value)=>{},必需

Ø onRejected函数:失败的回调函数(reason)=>{},可选

 指定用于得到成功value的成功回调和用于得到失败reason的失败回调返回一个新的Promise对象

3、Promise.prototype.catch方法:(onRejected)=>{}

Ø onRejected函数:失败的回调函数(reason)=>{}

 then()的语法糖,相当于then(undefined,onRejected)

4、Promise.resolve方法:(value)=>{}

Ø value:成功的数据或promise对象

 返回一个成功的promise对象

5、Promise.reject方法:(reason)=>{}

Ø reason:失败的原因

 返回一个失败的promise对象

6、Promise.all方法:(promises)=>{}

Ø promises:包含n个promises的数组

 返回一个新的promise,只有所有的promise都成功才是成功状态

7、Promise.race方法:(promises)=>{}

Ø promises:包含n个promises的数组

 返回一个新的promise,第一个完成的promise的结果状态就是最终的结果状态

评论

暂无评论