如何在Promise.catch执行后终止后续的Promise.then链式调用?
解决Promise链式调用在catch后终止的问题
你当前的代码里,catch执行后还会进入后续then,是因为**catch块如果没有显式抛出异常或返回pending状态的Promise,默认会返回一个resolved状态的空Promise**,所以链式调用会继续走到后面的then,导致输出两行日志。
下面是几种可行的解决方式:
方式一:调整then和catch的顺序(推荐)
把处理成功的then放在catch前面,这样只有前面的Promise都成功时才会执行成功回调,出错直接进入catch,不会触发后续的成功逻辑:
fetch('https://some.invalid.url') .then(resp => resp.text()) .then(text => console.log("got text: " + text)) .catch(err => console.log("got error: " + err));
方式二:在catch中返回pending状态的Promise
让catch返回一个永远处于pending状态的Promise,这样后续的then永远不会被执行,同时也不会触发unhandledrejection事件:
fetch('https://some.invalid.url').then(resp => resp.text()) .catch(err => { console.log("got error: " + err); return new Promise(() => {}); // 保持pending,终止链式调用 }) .then(text => console.log("got text: " + text));
方式三:使用async/await重构(更易读)
用async/await的写法可以让逻辑更直观,出错时直接在catch块处理,不会执行后续的成功代码:
async function fetchContent() { try { const resp = await fetch('https://some.invalid.url'); const text = await resp.text(); console.log("got text: " + text); } catch (err) { console.log("got error: " + err); } } fetchContent();
内容的提问来源于stack exchange,提问作者Kerrick Staley
相关产品推荐
相关产品推荐

