相信你们听过萧亚轩的【最熟悉的陌生人】,整首歌曲流露出一种深深的遗憾,曾经本身认为最熟悉的人,现在陌生的却像路人同样。。。。javascript
言尽于此,回归正题,最近在写一个组件的时候,发现本身曾经认为用的最熟练的 Promise 突然变得陌生起来,我想这仍是因为自身对 Promise 的认知不够致使,因此留下本文,以飨读者。java
引起我从新思考 Promise 用法的是以下一段代码:bash
new Promise(resolve=>{
console.log('p1');
resolve(1);
}).then(data=>{
console.log('then1');
console.log(data);
throw new Error('error1');
}).catch(err=>{
console.log(err);
return 'error1已处理';
}).then(data=>{
console.log('then2');
console.log(data);
});
复制代码
我以前的理解是,一旦 Promise 被 catch 捕获并执行以后,后续的 then 或者 catch 都不会再执行。 因此,个人理解程序应该输出以下的结果:测试
p1
then1
1
Error: error1
at <anonymous>
复制代码
按照我最初的理解,最后一个 then 不会再执行,可是事实倒是执行的,实际打印结果是:ui
p1
then1
1
Error: error1
at <anonymous>
then2
error1已处理
复制代码
看来,我仍是 too young,too simple
了。spa
上面这个现象说明了 Promise 的一个用法是,catch 只会捕获到以前 then 的异常, catch 捕获以后,若是以后仍有 then 任务,仍是会日后继续执行。code
下面几种例子均以两个 then 两个catch,互相衔接。来验证 Promise 的执行机制。cdn
new Promise(resolve=>{
console.log('p1');
resolve(1);
}).then(data=>{
console.log('then1');
console.log(data);
return 'then1 返回 2';
//throw new Error('error1');
}).catch(err=>{
console.log('接收then1异常', err);
return 'error1已处理';
}).then(data=>{
console.log('then2');
console.log(data);
}).catch(err=>{
console.log('接收 then2 异常', err);
});
复制代码
执行过程以下:blog
结果:ip
p1
then1
1
then2
then1 返回2
复制代码
第一个 then 中抛出异常。
new Promise(resolve=>{
console.log('p1');
resolve(1);
}).then(data=>{
console.log('then1');
console.log(data);
throw new Error('error1');
}).catch(err=>{
console.log('接收then1异常', err);
return 'error1已处理';
}).then(data=>{
console.log('then2');
console.log(data);
}).catch(err=>{
console.log('接收 then2 异常',err);
});
复制代码
执行过程以下:
结果:
p1
then1
1
接收then1异常 Error: error1
at <anonymous>:7:11
then2
error1已处理
复制代码
new Promise(resolve=>{
console.log('p1');
resolve(1);
}).then(data=>{
console.log('then1');
console.log(data);
throw new Error('error1');
}).catch(err=>{
console.log('接收then1异常', err);
throw new Error('error1已处理');
}).then(data=>{
console.log('then2');
console.log(data);
}).catch(err=>{
console.log('接收 catch1 异常',err);
});
复制代码
执行过程以下:
结果:
p1
then1
1
接收then1异常 Error: error1
at <anonymous>:7:11
接收 catch1 异常 Error: error1已处理
at <anonymous>:10:11
复制代码
综合以上三种常见用法,用四句话简单总结 Promise 机制:
简短的一片文章,但愿能给你们带来思考,高手能够略过~~ 勿喷~~