Home > OS >  Async/Await nested try/catch
Async/Await nested try/catch

Time:06-23

I have two similiar functions foo and bar that looks like this

async function foo() {
    try {
        await postRequest() 
    } catch (error) {
        throw error
    }

async function bar() {
    try {
        await anotherReq() 
    } catch (error) {
        // handle error
    }

I want to call foo first, handle the error by calling bar, then handle eventual bar errors again.

So i tried to do this

try {
    await foo();
} catch (error) {
    try {
        await bar()
    } catch(error) {
        // handle error
    }
}

But it's obviously ugly because of the nesting. Any workaround ?

CodePudding user response:

What I usually do with async/await to avoid the nesting is to return tupels of [result, error] instead of try/catch blocks.

So in this case my code would look something like this:

async function foo() {
  const response = await postRequest();

  if (response.ok) {
    return  [response, null];
  }

  return [null, "error"];
}

async function bar() {
  const response = await anotherReq();

  if (response.ok) {
    return  [response, null];
  }

  return [null, "error"];
}

// call functions
const [res, err] = await foo();

if (err) {
  const [res, err] = await bar();
}

CodePudding user response:

you can do like this

try {
    await foo();
    await bar();
} catch (error) {
   console.error(error)
}

  • Related