Return Promise.Reject() in Fetch
我正在用React构建一个应用程序,我想做的就是在某些情况下,以拒绝的Promise返回获取。这是我的代码的一部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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"(错误),我希望将提取结果视为拒绝。
在应用程序的其他地方,我有一个Promise。所有这些都调用了我刚刚编写的返回获取的方法。
1 2 3 4 5 6 | 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),我都需要抓住问题并显示正确的消息。
从运行时angular(暂时忽略TypeScript的类型),从
您无法将其扔到Promise中,并且仍然调用