JavaScript Asynchronous Programming with JavaScript Understanding Promises From Callbacks to Promises

Steve Seebart
Steve Seebart
Pro Student 11,896 Points

Moving error handling out of the promise

If I had multiple network request promises in my js file and the same block of error handling code for each, is there some way to move

xhr.onerror = () => reject(Error('A network error occurred.'));

into a reusable function?

Trying to find a way that would keep me from repeating the same code in each promise.

1 Answer

Steven Parker
Steven Parker
201,932 Points

What if you created a function that returns a function that calls "reject" with the desired argument:

const rejector = reject => () => reject(Error('A network error occurred.'));

And then called it when needed to set up an error handler:

xhr.onerror = rejector(reject);