如何跳过链式Promise中抛出异常的请求,不中断后续执行?
问题原因
你当前的try/catch包裹了整个循环逻辑,只要任意一次API请求抛出未捕获的异常,就会直接跳出循环进入全局的catch分支,后续的请求自然不会继续执行。
解决方案
将异常捕获逻辑移到循环内部,对每一次API请求单独做错误处理,捕获到异常后记录日志即可跳过当前请求继续执行后续逻辑。
修改后的代码如下:
callApis = async function () { var apis = ["apiWithSucess1", "apiWithException", "apiWithSucess1"]; var response = ""; for(var i = 0; i < apis.length; i++){ try { // 单次请求单独做异常捕获 const apiResponse = await httpRequest.get(apis[i]).promise(); response += apiResponse.data; } catch (err) { // 捕获到当前请求的异常,记录后继续下一次循环 console.log(`请求${apis[i]}出现异常 => `, err); } } return response; }; callApis().then(function(result){ console.dir(result); }).catch(function(err) { // 这里仅会在callApis函数本身出现非请求类异常时触发 console.log(err); });
可选优化方案
如果你不需要严格按照数组顺序执行API请求,想要提升执行效率,也可以用Promise.allSettled并发处理所有请求,之后过滤出成功的结果拼接即可,示例逻辑如下:
callApis = async function () { var apis = ["apiWithSucess1", "apiWithException", "apiWithSucess1"]; // 并发发起所有请求 const requestPromises = apis.map(api => httpRequest.get(api).promise()); // 等待所有请求完成,无论成功失败 const results = await Promise.allSettled(requestPromises); let response = ""; results.forEach((result, index) => { if (result.status === 'fulfilled') { response += result.value.data; } else { console.log(`请求${apis[index]}出现异常 => `, result.reason); } }) return response; };
内容的提问来源于stack exchange,提问作者StormTrooper
相关产品推荐
相关产品推荐

