XHR как Promise

Обернуть xhrRequest в Promise:

function xhrRequest (url, data, method = 'POST') {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onreadystatechange = () => {
		if (xhr.readyState != 4) return;
		if (xhr.status == 200) {
			resolve(xhr.response);
		} else {
			reject({
			  status: xhr.status,
			  statusText: xhr.statusText,
			  hText: 'response error'
			});
		}
	};
    xhr.onerror = () => {
      reject({
        status: xhr.status,
        statusText: xhr.statusText,
		hText: 'load error'
      });
    };
	xhr.withCredentials = true;
    xhr.send(data);
  });
}

export { xhrRequest };

Загрузка изображения:

function loadImage (url) {
	return new Promise((resolve, reject) => {
		let image = document.createElement('img');
		image.src = url;

		// Important success and error for the promise
        image.onload = function() {
          resolve(image);
        };
        image.onerror = function() {
          reject(url);
        };

	});
}

export { loadImage };

Использование:

let data = new FormData();
data.append('param1', value1);
data.append('param2', value2);
xhrRequest('/path/to/script/', data)
.then(
	(result) => {
		//parse JSON
		let object = JSON.parse(result);
		//do something
	}			
)
.catch((err) => console.log('Augh, there was an error!', err));

Изображение:

loadImage('/path/to/image.jpg')
.then((image) => {
	//do something
})
.catch((error) => {
	console.log('Augh, there was an error', src);
});