简体   繁体   中英

nested try, catch and async, await requests

I'm trying to make three requests using fetch(), each one depends on the results of the previous request. If any of the requests fail, I want to throw a custom error.

This pattern works except if the innermost request fails, it throws all three errors. If the middle request fails, it throws the middle and outer errors.

How can I fix this so it only throws the error from the level where the request fails? Is there a better way to write this?

 async function requests() { try { let response1 = await fetch(); if (response1.ok) { try { let response2 = await fetch(); if (response2.ok) { try { let response3 = await fetch(); if (response3.ok) { let jsonResponse3 = response3.json(); return jsonResponse3; } throw new Error('Request 3 failed'); } catch (error) { console.log(error); } } throw new Error('Request 2 failed'); } catch (error) { console.log(error); } } throw new Error('Request 1 failed'); } catch (error) { console.log(error); } } 

Try something like this.

 function dummyFetch() { return new Promise(resolve => { setTimeout(() => { resolve({ ok: true }) }, 500) }) } async function doAllSteps() { const response1 = await dummyFetch() if (!response1.ok) { throw new Error('foo') } const response2 = await dummyFetch() if (!response2.ok) { throw new Error('foo') } const response3 = await dummyFetch() if (!response3.ok) { throw new Error('foo') } const response4 = await dummyFetch() if (!response4.ok) { throw new Error('foo') } return 'you did it!' } function go() { return new Promise((resolve, reject) => { try { resolve(doAllSteps()) } catch (error) { reject(error) } }) } go().then((success) => { console.log(success) }) 

Can you do them one after another instead of nested?

async function requests() {
    try {
        let response1 = await fetch();
        throw new Error('Request 1 failed');
    } catch (error) {
        console.log(error);
    }
    if (response1 && response1.ok) {
        try {
            let response2 = await fetch();
            throw new Error('Request 2 failed');
        } catch (error) {
            console.log(error);
        }
    }
    if (response2 && response2.ok) {
        try {
            let response3 = await fetch();
            throw new Error('Request 3 failed');
        } catch (error) {
            console.log(error);
        }
    }
    if (response3 && response3.ok) {
        let jsonResponse3 = response3.json();
        return jsonResponse3;
    }
}

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