Skip to content
Advertisement

How do I promisify native XHR?

I want to use (native) promises in my frontend app to perform XHR request but without all the tomfoolery of a massive framework.

I want my xhr to return a promise but this doesn’t work (giving me: Uncaught TypeError: Promise resolver undefined is not a function)

JavaScript

Advertisement

Answer

I’m assuming you know how to make a native XHR request (you can brush up here and here)

Since any browser that supports native promises will also support xhr.onload, we can skip all the onReadyStateChange tomfoolery. Let’s take a step back and start with a basic XHR request function using callbacks:

JavaScript

Hurrah! This doesn’t involve anything terribly complicated (like custom headers or POST data) but is enough to get us moving forwards.

The promise constructor

We can construct a promise like so:

JavaScript

The promise constructor takes a function that will be passed two arguments (let’s call them resolve and reject). You can think of these as callbacks, one for success and one for failure. Examples are awesome, let’s update makeRequest with this constructor:

JavaScript

Now we can tap into the power of promises, chaining multiple XHR calls (and the .catch will trigger for an error on either call):

JavaScript

We can improve this still further, adding both POST/PUT params and custom headers. Let’s use an options object instead of multiple arguments, with the signature:

JavaScript

makeRequest now looks something like this:

JavaScript

A more comprehensive approach can be found at MDN.

Alternatively, you could use the fetch API (polyfill).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement