Another suggestion: when to throw outside the promise in a function parameter check

166 views
Skip to first unread message

Mörre Noseshine

unread,
Feb 22, 2016, 8:51:41 AM2/22/16
to Exploring ES6
Hi,

I found two subjects that I only discovered on my own despite having followed the blogs.

1) for which there actually are blog posts: should I throw or reject (or "return Promise.reject()") in a promise? Because throw works too.

2) When I check parameters in a function that returns promises, it seems obvious that this check should also take place in the promise - because errors of a function returning a promise are expected to be "in the promise", who wants to wrap a promise-returning function in try/catch?

But I think that SOME parameters should be checked outside the promise, so that when the check throws it is not caught by the promise.

Example for a case where checking IN the promise is better:

const readFile = function (file, encoding = null) {
return new Promise((/**Function*/ resolve, /**Function*/ reject) => {
// Thrown inside the promise because the value depends on (random) data being processed
if (!file) {
throw new TypeError('No file name given');
}

// .... <code>

});
};

Example for a case where checking OUTSIDE the promise is better:

const retry = function (fn, delay, retries) {
// Deliberately outside the promise: This should happen during development only because this
// is "static", not dependent on user data, and a forgotten catch() could lead to an error
// raised inside the promise to be silently dropped.
if (typeof fn !== 'function') {
throw new TypeError('No function given');
}

return new Promise((/**Function*/ resolve, /**Function*/ reject) => {
        // ... <code with calls to resolve() and to reject()>

});
};

This parameter is "static", it depends only on the code and not on user data. If a developer makes a parameter mistake (s)he may very well also make the (easier to make) mistake to not call catch() for the returned promise - and if the error was raised inside the promise it would be lost! And the parameter does not depend on data being processed, only on the code.

So I would propose to raise such errors outside the promise.

Axel Rauschmayer

unread,
Mar 5, 2016, 4:37:48 PM3/5/16
to Exploring ES6
More material for your blog post…
Reply all
Reply to author
Forward
0 new messages