运行如下测试代码:
function testPromise () {return new Promise((resolve, reject) => {setTimeout(() => {resolve('成功!')}, 1000)setTimeout(() => {reject('失败!')}, 3000)}).then((res) => {console.log('First then:', res)return 'From first then'}).catch(err => {console.log('First catch:', err)return 'From first catch'}).finally((res) => {console.log('First finally', res)return 'From first finally'}).then((res) => {console.log('Second then:', res)return 'From second then'}).catch(err => {console.log('Second catch:', err)return 'From second catch'}).finally((res) => {console.log('Second finally', res)return 'From second finally'}).then((res) => {console.log('Third then:', res)return 'From third then'}).catch(err => {console.log('Third catch:', err)return 'From third catch'}).finally((res) => {console.log('Third finally', res)return 'From third finally'})
}
结果分析:
-
一个promise中,resolve和reject只会执行最先触发的一个;
-
注释掉第6~8行代码,执行resolve的输出内容如下:
第一个then的参数是resolve的参数值,然后执行第一个finally;
第二个then的回调参数是第一个then的返回值,然后执行第二个finally,以此类推;
finally无参数; -
注释掉第3~5行代码,执行reject的输出内容如下:
reject抛出的错误会在第一个catch中捕获,参数是reject的参数值,接着执行第一个finally;继续会执行第二个then,参数是第一个catch的返回值,然后执行第二个finally;
以此类推; -
在第二个then或第二个catch中抛出一个异常,输出内容如下
在then中产生的错误不会在后面的catch中被捕获,而是继续执行后面的then和finally。
总结:
- 正常返回值时(resolve),连续多个then和finally均会被执行;
- reject抛出的错误只会被捕获一次,然后继续按顺序执行后面的then和finally,即使在then和finally中有错误抛出;
- then、catch的参数值是执行的上一个then或catch的返回值。