You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何在.then内检查result及result.id并抛出错误

如何在Promise的.then中校验结果并抛出错误?

原正常运行代码

.then((result) => { 
  this.triggerAction(result.id); 
}).catch((error) => { 
  this.errorMsg(error);
});

错误写法(语法不合法)

.then((result && result.id) => {
  this.triggerAction(result.id); 
}).catch((error) => { 
  this.errorMsg(error);
});

问题原因

箭头函数的参数定义位置只能声明参数变量,不能直接写条件表达式,(result && result.id)这种写法违反了函数参数的语法规则,导致报错。

正确实现方式

需要在.then的函数体内添加校验逻辑,若result或result.id不存在则主动抛出错误,错误会被后续的.catch捕获处理:

.then((result) => {
  // 校验result及result.id是否存在
  if (!result || !result.id) {
    throw new Error('响应数据不完整:缺少result或result.id');
  }
  this.triggerAction(result.id);
}).catch((error) => {
  this.errorMsg(error);
});

内容的提问来源于stack exchange,提问作者John Ken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:36:30