1

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();
}
3
  • It seems this is the way it is right now. Commented Jan 3, 2017 at 3:53
  • Can you elaborate on what you consider "cleaner"? Commented Jan 3, 2017 at 16:01
  • @jib - try/catch is not clean control structure. A rejected promise doesn't always mean an error, and an error at one level doesn't always constitute an error at a higher level (for instance fs.access throws if you can't access a file, but this is the appropriate way to check if you have access). try/catch is meant for unexpected errors, not expected ones. Commented Jan 3, 2017 at 18:30

1 Answer 1

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.