Skip to content

Instantly share code, notes, and snippets.

@norfish
Created July 30, 2018 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norfish/4a0946bcac2e8dd4a14e3152f80578ff to your computer and use it in GitHub Desktop.
Save norfish/4a0946bcac2e8dd4a14e3152f80578ff to your computer and use it in GitHub Desktop.
tiny xhr-ajax
const tinyAjax = function tinyAjax(config) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest()
request.open(config.method.toUpperCase(), config.url, true)
request.timeout = config.timeout || 60000
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || (request.readyState !== 4)) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
let responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
if (config.responseType === 'json') {
try {
responseData = JSON.parse(responseData)
} catch (error) {
reject(error, config, request)
}
}
resolve(responseData, config, request)
// Clean up request
request = null;
}
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject('Network Error', config, request);
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
reject(`timeout of ${config.timeout} ms exceeded`, config, request);
// Clean up request
request = null;
};
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment