node async/await -- do I need try/catch?

636 views Asked by At

I'm just playing around with async/await in node and it seems that if you're awaiting a promise and it gets rejected that it throws. I'm wondering if there is a cleaner pattern than going back to try/catch blocks that I'm not aware of?

async function foo() {
  const val = await Promise.reject();
}
1

There are 1 answers

0
jib On

try/catch() is the cleaner pattern, aligning synchronous and asynchronous error handling:

(Works in Chrome and Firefox Developer Edition at the moment)

function a(heads) {
  if (heads) throw new Error("Synchronous error");
}

async function b() {
  await Promise.resolve();
  throw new Error("Asynchronous error");
}

async function main(heads) {
  try {
    a(heads);
    await b();
  } catch (e) {
    console.log(e.message);
  }
}
main(false); // Synchronous error
main(true);  // Asynchronous error