0

I am using async await in my asynchronous code and want to bubble up the error to the asynchronous function which calls another asynchronous function inside it. I tried this and it worked but is it better if I returned Promise.reject(new Error("hi failed")) inside catch block iniside hi() or is there a better way to do this?

async function hi() {
  try {
    console.log("In hi");
    if (Math.random() < 0.5) throw new Error('error hi');
    else return Promise.resolve('hi resolved');
  } catch (error) {
    console.log("In hi error");
    throw error;
  } finally {
    console.log('hi finally');
  }
}

async function hey() {
  try {
    console.log("In hey");
    var data = await hi();
    console.log(data);
  } catch (error) {
    console.log("In hey error");
    console.log(error.message);
  }
}

hey();
Tom Gionfriddo
  • 410
  • 2
  • 8
noob_coder
  • 35
  • 2
  • 7
  • Use `throw`, it's more idiomatic, even more so inside an `async` function. – Bergi Aug 14 '21 at 06:26
  • Notice that `return Promise.reject(…)` works inside the `catch` block, but might not work as expected inside a `try` block. – Bergi Aug 14 '21 at 06:29

0 Answers0