Promise的Catch报错总结

在使用Promise时,异步返回的结果可能会两种,一种是使用resolve返回,另一种是使用reject返回。

当使用reject返回时,会throw一个Error出来。

这时的这个Error需要Catch住。

在Promise中Catch一个Error有两种。

第一种是在Then的回调中定义第二个参数:

先定义一个PromiseTest.html文件:

在文件上写下代码:

<script type="text/javascript">
	new Promise((resolve, reject) => {
	setTimeout(() => {
		// resolve('hello');
		// console.log("test");
		reject('hello2');
		console.log("test2");
	}, 1000)
}).then(
	(res)=> {  // 成功
		console.log("成功1"+res);
		return res; //当我们需要在传参给后面的then时,可以使用return来返回值
	},
 	(err) => {  // 失败
 		console.log("失败1"+err)
 		// reject(".............")
 		throw new Error('抛出一个错1') //throw和return一样会返回后面的值,所以当我们需要在传参给后面的catch时,可以使用throw来返回值
 	}
).then(
	(res) => {  // 成功
		console.log("成功2"+res);
	},
 	(err) => {  // 失败
 		console.log("失败2"+err)
 	}
)
</script>

之后,双击“PromiseTest.html”,可以在网页上查看结果:

 

第二种是定义Catch回调函数:

把“失败2”的回调移除,加上Catch回调:

<script type="text/javascript">
	new Promise((resolve, reject) => {
	setTimeout(() => {
		// resolve('hello');
		// console.log("test");
		reject('hello2');
		console.log("test2");
	}, 1000)
}).then(
	(res)=> {  // 成功
		console.log("成功1"+res);
		return res; //当我们需要在传参给后面的then时,可以使用return来返回值
	},
 	(err) => {  // 失败
 		console.log("失败1"+err)
 		// reject(".............")
 		throw new Error('抛出一个错1') //throw和return一样会返回后面的值,所以当我们需要在传参给后面的catch时,可以使用throw来返回值
 	}
).then(
	(res) => {  // 成功
		console.log("成功2"+res);
	}
).catch(
  (err) => {  // 失败
    console.log("Catch.....失败2"+err)
})
</script>

运行结果:

 最后,再来一个测试:

把“失败2”加回来:

<script type="text/javascript">
	new Promise((resolve, reject) => {
	setTimeout(() => {
		// resolve('hello');
		// console.log("test");
		reject('hello2');
		console.log("test2");
	}, 1000)
}).then(
	(res)=> {  // 成功
		console.log("成功1"+res);
		return res; //当我们需要在传参给后面的then时,可以使用return来返回值
	},
 	(err) => {  // 失败
 		console.log("失败1"+err)
 		// reject(".............")
 		throw new Error('抛出一个错1') //throw和return一样会返回后面的值,所以当我们需要在传参给后面的catch时,可以使用throw来返回值
 	}
).then(
	(res) => {  // 成功
		console.log("成功2"+res);
	},
 	(err) => {  // 失败
 		console.log("失败2"+err)
 	}
).catch(
  (err) => {  // 失败
    console.log("Catch.....失败2"+err)
})
</script>

查看运行结果:

“Catch.....失败2”又调用不到了,可以Then的第二个参数会屏蔽他后面的Catch回调。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值