a1exlism
2/25/2018 - 9:56 AM

XHR_with_promise

function getURL(url) {
	return new Promise(function(resolve, reject) {
		let req = new XMLHttpRequest();
		req.open('GET', url, true);
		req.onload = function() {
			if (req.status === 200) {
				resolve(req.responseText);
			} else {
				reject(new Error(req.statusText));
			}
		};
		req.onerror = function() {
			reject(new Error(req.statusText));
		};
    req.send();
	});
}

let URL = 'http://httpbin.org/get';
getURL(URL).then(function onFulfilled(data) {
  /*  usual with JSON format */
  console.log(data);
}).catch(function onRejected(error) {
  console.error(error);
});