I am writing a code that heavily uses ECMAScript 6-like promises in Javascript.
I cannot decide, if it's more "correct" to reject promise with a string or with an error, since I have seen both of these patterns being used.
That is, if it's better to call
return new Promise(response, reject) {
reject("Sky is falling.");
}
or
return new Promise(response, reject) {
reject(new Error("Sky is falling."));
}
A look at Mozilla's documentation is helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject
Promise.reject("Testing static reject").then(function(reason) { // not called }, function(reason) { console.log(reason); // "Testing static reject" }); Promise.reject(new Error("fail")).then(function(error) { // not called }, function(error) { console.log(error); // Stacktrace });
It shows both strings and errors as valid "reasons" for a rejection. The main thing (I think) is that the "reason" should be meaningful.
If a stack trace is helpful then it may be better to provide an error. If a simple string is all that's needed, then it will suffice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With