Want to promisify native XmlHttpRequest in JavaScript? Check this out!

For consulting and training, please write to us at info@xrmforyou.com
Promises in JavaScript have taken over by a storm. Gone are the days of nested successCallbacks and errorCallbacks.
But still XmlHttpRequest is being used every where and still remains the most popular to perform server HTTP requests. How about giving XmlHttpRequest a makeover.
So let’s redesign it a bit.
Why Most Redesigns Fail (and How to Make Sure Yours Doesn't ...
Below is my sample function where I would create a XmlHttpRequest and execute it.

function makeRequest(method, url, data) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open(method, url);
request.onload = resolve;
request.onerror = reject;
if (method === "POST")
request.send(data);
else
request.send();
});
}

And below is the sample code to call my function

makeRequest("GET", "<your url>", null)
.then(function (result) {
var req = result.target;
if (req.status === 200) {
// perform your logic here.
}
else {
// perform your logic here.
}
}, function (error) {
// handle errors.
});

As you can see from the above code, using very simple technique you can promisify your xmlhttprequest. If you observe we are handling the request status inside resolve handler only.
Keep in mind that this code will only fire the reject callback when onerror is called (network errors only) and not when the HTTP status code signifies an error.
Hope this helps!
Debajit Dutta
Microsoft Business Solutions MVP