promise
1.具有三种状态
pending(进行)、resolve(完成)、rejected(失败)。
可由pending变为resolve或pending变为rejected,一旦改变,状态凝固,无法再次改变。
2.基本用法
var promise=new Promise((resolve,reject)=>{
if(***){
resolve(success);
}else{
reject(error);
});
Promise实例接受一个函数作为参数,函数有两个参数,resolve和reject;
resolve表示异步操作执行成功后触发该回调函数,对应pending->resolve
reject表示异步操作失败后触发该回调函数,对应pending->rejected
所有回调函数在同步函数执行完后再执行
3.回调函数使用
实例生成后用then方法指定相应状态对应的回调函数
promise.then(function(success){
//success
},function(error){ //第二个为可选参数,可不写
//failure
})
then的链式调用:promise.then()返回的也是一个promise对象,也具有两个状态
promise.then(function(success){
return 'name'; //前一个then方法的返回值传给下一个then作为参数
}).then(function(name){ //获取上一个then传来的name
console.log(name);
},function(error){ //错误时进行调用
console.log('rejected');
})
4.catch
失败时进行的回调函数
promise.catch(function(error){
console.log(error);
})
等价于
promise.then(null,function(error){ //此方法不建议使用
console.log(error);
})
catch的链式调用:catch返回的也是一个promise对象,因为等价于then
promise.catch(function(){
throw new Error('this is error');
}).catch(function(e){
console.log(e); 输出'this is error',上一级error由下一级catch
})
5.Promise.all()
将多个promise合并为一个
var p=Promise.all([p1,p2,p3]);
状态相当于p1&&p2&&p3,都成功返回成功,其中一个失败返回失败
6.Promise.race()
传入多个promise最后生成一个
Promise.race([p1,p2,p3])
谁先状态发生改变,Promise就变成谁
7.Promise.resolve()
将其他对象转化为promise对象,默认为resolve
Promise.resolve('A'); //也可以不传入参数
相当于
new Promise(resolve=>{
resolve('A');
})
8.Promise.reject()
将其他对象转化为promise对象,默认为reject
var p=Promise.reject('error');
相当于
var p=new Promise((resolve,reject){
reject('error');
});
p.catch(function(e){
console.log(e);
})
9.done方法
Promise采用链式调用的方式,前面出现的错误后面可以catch到,但是最后一个catch抛出错误将无法捕获
p.catch(function(e){
console.log('a');
throw new Error('this is error');
}).catch(function(e){
console.log(e);
throw new Error('this is finally error'); //由于此错误在最后一个catch范围所以无法捕获
})
p.then().catch().then().done(); //done方法会捕获所有错误并抛出。
10.finally方法
正如这个英文单词的意思,finally()方法在promise最后调用,而且必须调用。