then((resolve)=>{},(reject)=>{});两个函数,第一个表示成功之后的处理,第二个表示失败的处理
- 1
如果只对失败进行处理,则第一个函数传null
then(null,(reject)=>{})
- 1
如果只对成功进行处理,则第二个函数可以不传
then((res)=>{});
- 1
当只对错误的进行处理时,等效于 使用catch();
catch(reject) == then(null,(reject)=>{});
- 1
then方法必定返回一个新的Promise;
可以理解为后续处理也是一个任务;
新任务的状态取决于后续处理:
- 若没有相关的后续处理,新任务的状态和前任务一致,数据为前任务的数据
- 若有后续处理但还未执行,新任务挂起;
- 若后续处理执行了,则根据后续处理的情况,确定新任务的状态
- 后续处理执行无错,新任务的状态为完成,数据为后续处理的返回值;
- 后续执行有错,新任务的状态为失败,数据为异常对象;
- 后续执行后返回的是一个任务的对象,新任务的状态和数据,与该任务对象一致;
const pro = new Promise((resolve)=>{ console.log("学习"); resolve(); }); const pro2 = pro.then(()=>{ console.log('考试') }); console.log(pro2);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
总之:后面任务的状态,如果有相关的处理,一定要看处理的过程,不管是对成功的处理,还是对失败的处理;如果前面的任务成功了,就看成功的处理,如果前面的任务失败了,就看失败的处理;看处理的过程有没有问题,如果没有问题,pro2就成功,有问题就失败。
总结:
// 任务成功后,执行处理,失败则执行处理
pro.then(成功处理1).catch(失败处理2);
// 任务成功后,依次执行处理1,2
pro.then(处理1).then(处理2);
// 任务成功后,依次执行处理1,处理2、若任务失败或前面的处理有错,执行3
pro.then(处理1).then(处理2).catch(处理3);
Promise.resolve(data); 直接返回一个完成状态的任务
Promise.reject(data); 直接返回一个拒绝状态的任务
Promise.all(任务数组); 返回一个任务
任务数组全部成功则成功,任何一个失败则失败
const pro = Promise.all([ Promise.resolve(1), Promise.reject(2), Promise.resolve(3), ]); setTimeout(()=>{ console.log(pro); // rejected 2; },1000)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- Promise.any(任务数组) 返回一个任务
任务数组任一成功则成功,任务全部失败则失败
const pro = Promise.all([ Promise.resolve(1), Promise.reject(2), Promise.resolve(3), ]); setTimeout(()=>{ console.log(pro); // fulfilled 1; },1000)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Promise.allSettled(任务数组) 返回一个任务
任务数组全部已决则成功,任务全部失败则失败
Promise.race (任务数组) 返回一个任务
任务数组任一已决则已决,状态和其一致。
有了Promise之后,异步任务有了一种统一的处理方式
有了统一的处理方式,ES官方就可以对其进一步优化
ES7退出了两个关键字
async和await,用于更加优雅的表达Promise;
async关键字用于修饰函数,被它修饰的函数,一定返回Promise
async function method1(){
return 1; // 该函数返回值是Promise完成后的数据
}
method(); // Promise { 1 }
async function method2(){
return Promise.resolve(1); // 若返回的是Promise,则method2得到的Promise状态和其一致。相当于没有写async
}
method2(); // Promise { 1 }
async function method3(){
throw new Error(1); // 若执行过程报错,则任务是rejected
}
method3();
await关键字表示等待某个Promise完成,它必须用于async函数中
async function method(){
const n = await Promise.resolve(1);
console.log(n);
}
// 上面代码等同于
function method(){
return new Promise((resolve,reject)=>{
Promise.resolve(1).then(n=>{
console.log(n);
resolve(1);
})
})
}
await也可以等待其他数据
async function method(){
const n = await 1; // 等同于await Promise.resolve(1);
}
method();
async function test(){
return 123;
}
async function m(){
const data = await test();
console.log(data);
}
m();
如果需要针对失败的任务进行处理,可以使用try-catch 语法
async function method(){
try{
const n = await Promise.reject(123); // 失败
console.log('成功'、,n);
}
catch(err){
console.log('失败',err);
}
}