Skip to content

Instantly share code, notes, and snippets.

@dgraham
Last active March 24, 2023 15:44
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dgraham/92e4c45da3707a3fe789 to your computer and use it in GitHub Desktop.
Save dgraham/92e4c45da3707a3fe789 to your computer and use it in GitHub Desktop.
Simple window.fetch wrapper.
(function() {
function status(response) {
if (response.ok) {
return response
} else {
var error = new Error(response.statusText || response.status)
error.response = response
throw error
}
}
function headers(options) {
options = options || {}
options.headers = options.headers || {}
options.headers['X-Requested-With'] = 'XMLHttpRequest'
return options
}
function credentials(options) {
if (options == null) {
options = {}
}
if (options.credentials == null) {
options.credentials = 'same-origin'
}
return options
}
function json(response) {
return response.json()
}
function text(response) {
return response.text()
}
$.fetch = function(url, options) {
options = headers(credentials(options))
return fetch(url, options).then(status)
}
$.fetchText = function(url, options) {
options = headers(credentials(options))
return fetch(url, options).then(status).then(text)
}
$.fetchJSON = function(url, options) {
options = headers(credentials(options))
options.headers['Accept'] = 'application/json'
return fetch(url, options).then(status).then(json)
}
$.fetchPoll = function(url, options) {
return new Promise(function(resolve, reject) {
function poll(wait) {
function done(response) {
switch (response.status) {
case 200:
resolve(response)
break
case 202:
setTimeout(poll, wait, wait * 1.5)
break
default:
var error = new Error(response.statusText || response.status)
error.response = response
reject(error)
break
}
}
$.fetch(url, options).then(done, reject)
}
poll(1000)
})
}
}).call(this);
@westdavidr
Copy link

This is awesome.

When I get an error response (like a 401 unauthorized) how do you handle that?

EDIT: I guess what I mean is, how do I get the error message from the server?

@masad-frost
Copy link

Just to point out, jQuery doesn't throw on 304 and some other 300 codes.

@niftylettuce
Copy link

see https://github.com/glazedio/frisbee if you need something more advanced

@elbywan
Copy link

elbywan commented Sep 19, 2017

In the same vein as this gist, this lib is a tiny wrapper around fetch with a pleasant syntax.

@aserr13
Copy link

aserr13 commented Jul 1, 2021

This is awesome.

When I get an error response (like a 401 unauthorized) how do you handle that?

EDIT: I guess what I mean is, how do I get the error message from the server?
Try to download the system bin and complete it with a new launch code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment