简体   繁体   English

在提取中返回Promise.Reject()

[英]Return Promise.Reject() in Fetch

I'm building an App with React and what I want to do is to return a fetch as rejected Promise if certain conditions happen. 我正在用React构建一个应用程序,我想做的就是如果发生某些情况,将获取的内容作为拒绝的Promise返回。 This is (part of) my code: 这是我的代码(的一部分):

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().
    })
);

So, basically, if 'data.code' is equal to "ER" (Error), I want the fetch to be evaluated as reject. 因此,基本上,如果“ data.code”等于“ ER”(错误),我希望将提取结果视为拒绝。

In some other point of the Application, I've a Promise.All that calls the method in which there is the return fetch I've just written. 在应用程序的其他方面,我有一个承诺,所有这些都调用了我刚刚编写的返回获取的方法。

let fetch1 = this.handleEmailAndNameSubmit(undefined, true);
let fetch2 = this.handlePasswordSubmit(undefined, true);

Promise.all([fetch1, fetch2]).then(() => {
    (this.state.lastLinkClicked).click();
}));

EDIT: First problem was result (or at least, the reason why it happened).. 编辑:第一个问题是结果(或至少是它发生的原因)。

Having the catch statement, the 'Throw new Error' is caught by it, and the Promise.all can enter its .then().. But I would like to keep that catch statement because, if the fetch would fail for any reason that are not connected to the data.code (like impossibility to connect to the URI), I need to catch the problem and display a proper message. 有了catch语句后,它就会捕获“引发新错误”,并且Promise.all可以输入其.then()。。但是我想保留该catch语句,因为如果由于任何原因导致提取失败,没有连接到data.code(例如无法连接到URI),我需要抓住问题并显示正确的消息。

From the runtime perspective (ignoring TypeScript's types for a moment), throw new Error('foo'); 从运行时的角度(暂时忽略TypeScript的类型), throw new Error('foo'); and return Promise.reject(new Error('foo')); return Promise.reject(new Error('foo')); are exactly the same when done from inside a .then() handler. .then()处理程序内部完成时,它们完全相同。

There's no way you are throwing inside of a Promise and Promise.all().then() is still called, Promise.all() will reject on the first rejection of the passed Promise array. 您无法将其扔到Promise中,并且Promise.all().then()仍然被调用, Promise.all()将在第一次拒绝传递的Promise数组时拒绝。

throw ing should be safe, make sure you actually hit the throw , and make sure you're Promise.all() ing on the right Promises. throw应该是安全的,请确保您确实击中了throw ,并确保您在正确的Promises上处于Promise.all()上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM