欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Promise多个then、catch、finally的执行结果分析与总结

程序员文章站 2023-12-31 22:44:58
运行如下测试代码:function testPromise () {return new Promise((resolve, reject) => {setTimeout(() => {resolve('成功!')}, 1000)setTimeout(() => {reject('失败!')}, 3000)}).then((res) => {console.log('First then:', res)return 'Fr...

运行如下测试代码:

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'
	})
}

结果分析:

  1. 一个promise中,resolve和reject只会执行最先触发的一个;
  2. 注释掉第6~8行代码,执行resolve的输出内容如下:
    Promise多个then、catch、finally的执行结果分析与总结
    第一个then的参数是resolve的参数值,然后执行第一个finally;
    第二个then的回调参数是第一个then的返回值,然后执行第二个finally,以此类推;
    finally无参数;
  3. 注释掉第3~5行代码,执行reject的输出内容如下:
    Promise多个then、catch、finally的执行结果分析与总结
    reject抛出的错误会在第一个catch中捕获,参数是reject的参数值,接着执行第一个finally;继续会执行第二个then,参数是第一个catch的返回值,然后执行第二个finally;
    以此类推;
  4. 在第二个then或第二个catch中抛出一个异常,输出内容如下
    Promise多个then、catch、finally的执行结果分析与总结
    在then中产生的错误不会在后面的catch中被捕获,而是继续执行后面的then和finally。

总结:
1. 正常返回值时(resolve),连续多个then和finally均会被执行;
2. reject抛出的错误只会被捕获一次,然后继续按顺序执行后面的then和finally,即使在then和finally中有错误抛出;
3. then、catch的参数值是执行的上一个then或catch的返回值。

本文地址:https://blog.csdn.net/Liuer_Qin/article/details/110230078

相关标签: js es6

上一篇:

下一篇: