[英]Return Promise.Reject() in Fetch
我正在用React构建一个应用程序,我想做的就是如果发生某些情况,将获取的内容作为拒绝的Promise返回。 这是我的代码(的一部分):
return (fetch(controllerURI, {
method: 'post',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify({
"userId": this.state.userEmailAndName.userId,
"name": this.state.userEmailAndName.name,
"newEmail": this.state.userEmailAndName.newEmail
})
})
.then(response => response.json()).then(data => {
if (data.code == "ER")
Throw new Error("ERROR");
})
.catch(e => {
console.log("Inside catch");
// This catch caught the Throw Error in .then().
})
);
因此,基本上,如果“ data.code”等于“ ER”(错误),我希望将提取结果视为拒绝。
在应用程序的其他方面,我有一个承诺,所有这些都调用了我刚刚编写的返回获取的方法。
let fetch1 = this.handleEmailAndNameSubmit(undefined, true);
let fetch2 = this.handlePasswordSubmit(undefined, true);
Promise.all([fetch1, fetch2]).then(() => {
(this.state.lastLinkClicked).click();
}));
编辑:第一个问题是结果(或至少是它发生的原因)。
有了catch语句后,它就会捕获“引发新错误”,并且Promise.all可以输入其.then()。。但是我想保留该catch语句,因为如果由于任何原因导致提取失败,没有连接到data.code(例如无法连接到URI),我需要抓住问题并显示正确的消息。
从运行时的角度(暂时忽略TypeScript的类型), throw new Error('foo');
并return Promise.reject(new Error('foo'));
从.then()
处理程序内部完成时,它们完全相同。
您无法将其扔到Promise中,并且Promise.all().then()
仍然被调用, Promise.all()
将在第一次拒绝传递的Promise数组时拒绝。
throw
应该是安全的,请确保您确实击中了throw
,并确保您在正确的Promises上处于Promise.all()
上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.