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

运行如下测试代码:

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的输出内容如下:
    20201127142914354
    第一个then的参数是resolve的参数值,然后执行第一个finally;
    第二个then的回调参数是第一个then的返回值,然后执行第二个finally,以此类推;
    finally无参数;

  3. 注释掉第3~5行代码,执行reject的输出内容如下:
    20201127143859436
    reject抛出的错误会在第一个catch中捕获,参数是reject的参数值,接着执行第一个finally;继续会执行第二个then,参数是第一个catch的返回值,然后执行第二个finally;
    以此类推;

  4. 在第二个then或第二个catch中抛出一个异常,输出内容如下
    20201127152623794
    在then中产生的错误不会在后面的catch中被捕获,而是继续执行后面的then和finally。

总结:

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

补充:

new Promise((resolve, reject) => {
	resolve('成功!'); // 会执行,promise返回fullfild
	reject('失败!'); // 会执行,但不会响应reject
    debugger; // 会执行
})
posted @ 2025-10-21 12:27  阿木隆1237  阅读(36)  评论(0)    收藏  举报