一、谈一谈 promise
Promise是一种用于解决异步问题的思路、方案或者对象方式。在js中,经常使用异步的地方是Ajax交互。比如在es5时代,jQuery的ajax的使用success来完成异步的:1
2
3
4
5$.ajax({
url:'/xxx',
success:()=>{},
error: ()=>{}
})
但当存在多个回调函数时,可能会产生回调地狱。
ES6中的promise提供了一个then,来为异步提供回调函数:1
2
3
4
5
6
7$.ajax({
url:'/xxx',
}).then( ()=>{
// 成功的回调
}, ()=>{
// 失败的回调
})
一个具有多个回调的promise对象
1 | fn = new Promise(function (resolve, reject) { |
Promise的原理
在Promise的内部,有一个状态管理器的存在,有三种状态:pending、fulfilled、rejected。
(1) promise 对象初始化状态为 pending。
(2) 当调用resolve(成功),会由pending => fulfilled。
(3) 当调用reject(失败),会由pending => rejected。
因此,看上面的的代码中的resolve(num)其实是将promise的状态由pending改为fulfilled,然后向then的成功回掉函数传值,reject反之。但是需要记住的是注意promsie状态 只能由 pending => fulfilled/rejected, 一旦修改就不能再变(记住,一定要记住,下面会考到)。
当状态为fulfilled(rejected反之)时,then的成功回调函数会被调用,并接受上面传来的num,进而进行操作。promise.then方法每次调用,都返回一个新的promise对象 所以可以链式写法(无论resolve还是reject都是这样)。
Promise的几种方法
then
then方法用于注册当状态变为fulfilled或者reject时的回调函数:1
2
3// onFulfilled 是用来接收promise成功的值
// onRejected 是用来接收promise失败的原因
promise.then(onFulfilled, onRejected);
需要注意的地方是then方法是异步执行的。
1 | // resolve(成功) onFulfilled会被调用 |
catch
catch在链式写法中可以捕获前面then中发送的异常。
1 | fn = new Promise(function (resolve, reject) { |
其实,catch相当于then(null,onRejected),前者只是后者的语法糖而已。