promise简介:
Promise的出现,原本是为了解决回调地狱的问题.
通过把异步中使用回调函数的场景改为了.then()
、.catch()
等函数链式调用的方式。基于promise
我们可以把复杂的异步回调处理方式进行模块化。
promise原理:
其实promise
原理说起来并不难,它内部有三个状态,分别是pending
,fulfilled
和rejected
。
pending
是对象创建后的初始状态,当对象fulfill
(成功)时变为fulfilled
,当对象reject
(失败)时变为rejected
。不可逆向,且一旦状态改变就不会再变
promise使用:
Promise
对象拥有两个实例方法then()
和catch()
。
then
方法可以接收两个参数, 第一个参数会添加到fulfill
时调用的数组中,第二个参数添加到reject
时调用的数组中。当promise
状态fulfill
时,会把resolve(value)
中的value
值传给调用的函数中,同理,当promise
状态reject
时,会把reject(reason)
中的reason
值传给调用的函数。例:
promise例子:
//例子--模仿去读取一个json
async function asyncReadFile(int){
console.log(int); //打印1
let result = await new Promise((resolve,reject)=> {
console.log(2); //打印2
ajax({
method: 'get',
url: './file.json',
success(response) {
console.log(response); //打印结果
resolve('resolved');
},
fail(err) {
reject(err);
}
});
}).then((msg)=>{console.log(msg+'!!!')}); //成功打印出resolved!!!
//result的值是await内部通过resolve传出来的值
console.log(3); //打印3
};
asyncReadFile(1).then((msg='msg')=>{console.log(msg+'1');return 'msg'+'1'}) //打印msg1
.then((msg)=>{console.log(msg+'2');return msg+'2'}) //打印msg12
.then((msg)=>{console.log(msg+'3');throw new Error('404');return msg+'3'}) //打印msg123
.catch((err)=>{console.error('错误是'+err)}); //打印'错误是404'
结果如下:
promise注意点:
1.then
方法会返回一个新的promise
,下面的例子中p == p1
将返回false
,说明p1
是一个全新的对象。虽然它也是链式调用的,它是在新的对象上添加成功或失败的回调,这与jQuery
中的链式调用不同。
2. 如果promise.then(undefined,fnFail).then(fnSuccess)中resolve()调用成功函数 , 可以调用到fnSuccess函数 , 同理在reject中也可以这么执行. 当对应的参数不为函数时,会将前一promise
的状态和值传递下去。
3.所以我们可以在多个then
之后添加一个catch
方法,这样前面只要reject
或抛出异常,都会被最后的catch
方法处理。