1

This is not any conceptual question. just want to correct my logical side.

Case 1:

try {
  var to = await new IamErrorAlways()

  if (to && to instanceof Error) return to // is this correct way to handle.
} catch (error) {
  // report failure.
  return error
}

Case 2:

try {
  var to = await new IamErrorAlways()

  if (!to) throw new error('Expected to to return error') // or is this correct way to handle.
} catch (error) {

  // report failure.
  return error // <---- catch will return awaited error
}

Out of both which one is good.

5
  • It’s likely that neither one is correct. await new … never makes sense unless the constructor produces a thenable, and similarly !to can never be true unless new IamErrorAlways() is a thenable. Commented Dec 15, 2019 at 8:05
  • :p it make sense when your constructor is awaited and !to could be this itself..which should not be empty in return Commented Dec 15, 2019 at 8:09
  • What does “when your constructor is awaited” mean? Commented Dec 15, 2019 at 8:11
  • Constructor always returns immediate and then is what get resolved in end. i agree...but for cases when you want await method calls inside function body than you have to wrap it up with async...and if you do that than it became obvious to use await new functionName() else you have to resolve it. Commented Dec 15, 2019 at 8:41
  • 1
    It’s not clear what you mean, but it doesn’t sound like the only reason to use await new, which is the thenable thing that I mentioned. If !('then' in new IamErrorAlways()), var to = await new IamErrorAlways(); is exactly equivalent to await; var to = new IamErrorAlways();, and probably equivalent to var to = new IamErrorAlways();. Commented Dec 15, 2019 at 8:45

1 Answer 1

1

Whenever promise rejects, it will not be returned as a value it will be thrown. And only way to check for thrown error is to catch it.

This is a typical example of a promise being rejected:

const promise = function() {
  return Promise.reject('hello');
};

(async () => {
  try {
    const promiseVal = await promise();
    console.log(promiseVal);
  } catch (err) {
    console.log(err+' from error');
  }
})();

So in this case the console.log in try block won't even execute. The catch will be executed printing hello from 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.