Skip to content

Instantly share code, notes, and snippets.

@NekR
Last active August 29, 2015 14:17
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 NekR/4bb5190e451d164d17b1 to your computer and use it in GitHub Desktop.
Save NekR/4bb5190e451d164d17b1 to your computer and use it in GitHub Desktop.
fetch -- other way

Pseudo-JavaScript code with inline comments:

// why not just new Fetch? hah
window.fetch = function(url, other) {
  return new Fetch(url, other);
};

class Fetch {
  cancel() {} // it absolutely should be cancelable!

  _exitHelper() {
    if (this._error) {
      return this._errorPromise;
    }

    if (this._canceled) {
      return this._foreverPendingPromise;
    }
  },

  get headers() {
    var exit = this._exitHelper();

    if (exit) {
      return exit;
    }

    return this._headersPromise;
  },

  constructor(url, other) {
    this.response = new Promise(function() {
      // resolve once network operation completely ended
    });
  }
}
var req = fetch('...');

req.headers.then(function(response) {
  if (response.headers.get('Content-Type') === 'application/json') {
    return response.json();
  }

  req.cancel(); // accept only json
});
var req = fetch('...');

req.headers.then(function(response) {
  var reader = response.body.getReader();
  // ...
});
var req = fetch('...');

req.response.then(function(response) {
  // fully done here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment