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
相关产品推荐
相关产品推荐

