Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Last active March 15, 2017 00:20
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 nijikokun/b187fbfcfc2ca1a1c6bb3d6f32071066 to your computer and use it in GitHub Desktop.
Save nijikokun/b187fbfcfc2ca1a1c6bb3d6f32071066 to your computer and use it in GitHub Desktop.
XHR Promisified

Fetch (xhr promisified)

Lightweight implementation of fetch api

Usage

import fetch from './fetch'

API

  • fetch(url[, options])

    fetch('https://google.com')
      .then(response => console.log(response))
      .catch(error => console.log(error))

    Options

    • method - http method (default is GET)
    • decoder - body decoder (default is JSON.parse, for none set to null)
    • headers - http headers
    • body - http payload (only supported on methods other than GET)

    Response Object

    • status - response status code
    • statusText - response status text
    • body - decoded or raw body depending on decoder setting
    • rawBody - raw response body
    • request - xhr request object
export default function (url, options) {
options = options || {
method: 'GET',
decoder: JSON.parse,
headers: {},
body: null
}
return new Promise((resolve, response) => {
let xhr = new XMLHttpRequest()
let headers = Object.keys(options.headers)
let data = options.body
xhr.open(options.method, url)
xhr.onload = () => {
let method = this.status > 300
? reject
: resolve
return method({
status: this.status,
statusText: xhr.statusText,
body: options.decoder ? options.decoder(xhr.response) : xhr.response,
rawBody: xhr.response,
request: xhr
})
}
xhr.onerror = () => {
return reject(new Error("unable to complete " + options.method + " request for: " + url))
}
headers.forEach(key => xhr.setRequestHeader(key, options.headers[key]))
if (options.method !== 'GET') {
if (data && typeof data === 'object') {
data = Object
.keys(data)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
}
xhr.send(data)
} else {
xhr.send()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment