[英]how to check conditions inside .then in javascript
现有代码(工作正常):
.then((result) => {
this.triggerAction(result.id);
}).catch((error) => {
this.errorMsg(error);
});
当我尝试在 .then 中添加条件时会引发错误。
.then((result && result.id) => {
this.triggerAction(result.id);
}).catch((error) => {
this.errorMsg(error);
});
我需要检查 result 和 result.id 是否出现在响应中,如果结果中不可用则抛出错误 id 。
如果result.id
丢失,要抛出错误,您应该执行以下操作:
.then((result) => {
if(!result.id) {
throw new Error("result.id is missing!");
}
this.triggerAction(result.id);
}).catch((error) => {
this.errorMsg(error);
});
如果您只想将result
传递给.catch()
块,也可以throw result
.then((result) => {
result?.id && this.triggerAction(result.id);
})
.catch((error) => {
this.errorMsg(error);
});
.then中的结果是您收到的成功响应。 您不能在函数参数中动态应用条件。 您必须检查回调函数内部。 如果结果将具有id (result?.id) 则this.triggerAction(result.id)将调用
我希望它会奏效。
谢谢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.