Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created May 9, 2018 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/e592755a1e5fecf6a1cc25fc593b1239 to your computer and use it in GitHub Desktop.
Save xeoncross/e592755a1e5fecf6a1cc25fc593b1239 to your computer and use it in GitHub Desktop.
HTML5 / Node V8 `fetch()` does not support progress events so you have to use the XHR / XMLHttpRequest object. Here is a simple ES6 + promises wrapper by @caub
// https://github.com/github/fetch/issues/89#issuecomment-256610849
function futch(url, opts={}, onProgress) {
return new Promise( (res, rej)=>{
var xhr = new XMLHttpRequest();
xhr.open(opts.method || 'get', url);
for (var k in opts.headers||{})
xhr.setRequestHeader(k, opts.headers[k]);
xhr.onload = e => res(e.target.responseText);
xhr.onerror = rej;
if (xhr.upload && onProgress)
xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
xhr.send(opts.body);
});
}
futch('/').then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment