在使用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回调。