关于javascript:在抓取中返回Promise.Reject()

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的类型),从.then()处理程序内部进行操作时,throw new Error('foo');return Promise.reject(new Error('foo'));完全相同。

您无法将其扔到Promise中,并且仍然调用Promise.all().then()Promise.all()将在第一次拒绝所传递的Promise数组时拒绝。

throw ing应该是安全的,请确保您确实击中了throw,并确保您在正确的Promises上进行了Promise.all() ing。