1

Essentially I have an async function containing a try/catch that calls another async function also containing a try catch, and I'm getting a bit confused about how to properly implement what I'm doing. Some "pseudocode" showing my current implementation:

const main = async () => {
  try {
    const test = await secondFunc();
    console.log(test);

  } catch(err) {

    console.log('Found an error!');
    console.log(err);
  }

const secondFunc = async () => {
  try {
    await performSomeRequestExample();

  } catch(err) {
    if (err.x === 'x') {
      doSomething();
    } else {

      //********
      throw err;
      //********
  }

}

So what I'm trying to do is get the throw(err) (surrounded by the asterisks) to be caught by the catch in main() which will also call the console.log('Found an error!'), but what currently happens is the error is thrown from secondFunc(), the catch in main() is never hit and I get an unhandled promise rejection.

Any guidance on what I'm doing wrong?

2
  • Is your else ever reached? Also does anything change if you put a variable in front of that await in your second function? Commented Apr 19, 2020 at 13:33
  • 1
    Please provide a minimal reproducible example. Commented Apr 19, 2020 at 13:40

4 Answers 4

3

My advice is to minimize using try/catch unless absolutely necessary. With async functions (or any functions that return a Promise object) you can usually simplify things by not worrying about try/catch blocks unless you need to do something specific with certain errors. You can also use .catch rather than try/catch blocks to make things easier to read.

For example your code above could be written like this:

const main = async () => {
  const test = await secondFunc().catch(err => {
    console.log("Found an error from secondFunc!", err);
    throw err;  // if you want to send it along to main's caller
  });
  if (test) {
    console.log("Test", test);
  }
};

const secondFunc = () => {
  return performSomeRequestExample().catch(err => {
    if (err.x === "x") {
      doSomething();
    } else {
      throw err;
    }
  });
};

const performSomeRequestExample = () => Promise.reject("bad");

main().then(
  () => console.log("worked"),
  err => console.log("failed from main", err)
);

In secondFunc we don't need to use async since we can just return the promise coming back from performSomeRequestExample and handle any failures in the .catch.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't assume he doesn't need the second function to be async for all you know performSomeRequestExample() is a fetch and needs to await and on top of that OP's code is incomplete and not reflective of what they really have.
True. If performSomeRequestExample doesn’t return a Promise then you could make it async or return a Promise that resolves to its return value
0

You should use

const secondFunc = async () => {
  performSomeRequestExample().then(res =>{
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  }
)

Comments

0

Add a return before the await of performSomeRequestExample.

const secondFunc = async () => {
    try {
        return await performSomeRequestExample();
    } catch (err) {
        if (err.x === 'x') {
            console.log('x');
        } else {
            throw err;
        }
    }
}

or you can also use .catch() after the awaited function.

Comments

0

Another solution can be like this

const main =  async() => {
try {
    const test = await secondFunc();
    console.log(test);

  } catch(err) {

    console.log('Found an error!');
    console.log(err);
  }
}

const secondFunc = async () => {
  //return await performSomeRequestExample();  //for success
  return await performSomeRequestExample(2); //for error
}

const performSomeRequestExample = async(abc=1) => {
  return new Promise(function(resolve,reject){
    if(abc ==1){
      setInterval(resolve("yes"),400);
    }else{
      setInterval(reject("opps"),400);
    }
  });
}


main();

Test this code at this link: https://repl.it/repls/JoyfulSomberTelevision

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.