Skip to content

Instantly share code, notes, and snippets.

@dgraham dgraham/fetch.js
Last active Jul 14, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Oct 26, 2015

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

This comment has been minimized.

Copy link

commented Feb 12, 2016

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

@niftylettuce

This comment has been minimized.

Copy link

commented May 25, 2016

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

@elbywan

This comment has been minimized.

Copy link

commented Sep 19, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.