简体   繁体   中英

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. 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.

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.

From the runtime perspective (ignoring TypeScript's types for a moment), throw new Error('foo'); and return Promise.reject(new Error('foo')); are exactly the same when done from inside a .then() handler.

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.

throw ing should be safe, make sure you actually hit the throw , and make sure you're Promise.all() ing on the right Promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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