Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }
}
like image 450
Ryan K Avatar asked Nov 27 '22 01:11

Ryan K


1 Answers

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)
})
like image 148
sgb Avatar answered Dec 04 '22 12:12

sgb