2

I am working with Promises and found that when rejecting is recommended to pass an Error() object as argument in order to enable error handling.

I find some examples where a new Error() is given and some others where only Error() is passed.

After testing several cases I just do not find any difference between one usage and other, as seen here where both rejects seem to behave exactly the same:

const p = new Promise((resolve, reject) => {

    setTimeout(reject, 1000, Error("Nope...")); 
    //setTimeout(reject, 1000, new Error("Nope..."));       
});    


p.then(val => { console.log(val) })
.catch(error  => { console.error(error.message) });

In this case, which practical difference is between both error handling ways?

Biomehanika
  • 1,530
  • 1
  • 17
  • 45
  • I should have know this was a duplicate question. If you'll un-accept, I'll delete my answer. (Duplicate questions aren't necessarily a bad thing. In this case, I don't think my answer adds much of anything that isn't covered by the dupetarget's answers.) – T.J. Crowder Dec 10 '18 at 07:42

1 Answers1

2

After testing several cases I just do not find any difference between one usage and other...

That's because when you call Error as a function (without new), it acts exactly like you'd called it with new. That is, Error(x) and new Error(x) do exactly the same thing. This is a "feature" of the Error function. Normally, there's a difference between calling a function without new and calling it with new, just not in this case.

From the spec:

The Error constructor:

  • ...
  • ...
  • creates and initializes a new Error object when called as a function rather than as a constructor. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.
  • ...
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875