Skip to content

Instantly share code, notes, and snippets.

@bhstahl
Created October 14, 2015 21:56
Show Gist options
  • Save bhstahl/06a82b4362057d021c52 to your computer and use it in GitHub Desktop.
Save bhstahl/06a82b4362057d021c52 to your computer and use it in GitHub Desktop.
ES2015: a Promise for simpler networking

ES2015: a Promise for simpler networking


XHR & FETCH

    var xhr = new XMLHttpRequest();     fetch(url)
    xhr.open('GET', url);                 .then(res => res.json())
    xhr.responseType = 'json';            .then(console.log)
    xhr.onload = function() {             .catch(console.warn)
      console.log(xhr.response);
    };

    xhr.onerror = function() {
      console.log("Whoops");
    };

    xhr.send();

2009 → 2015

  • API driven development
  • Users don't expect to refresh
  • Resource rich web applications

Promises

            import Q from 'q';                    getAjax(`/user/${user.id}`)
                                                    .then(handleSuccess)
            let getAjax = (url) => {                .catch(handleError)
              let deferred = Q.defer();
              let xhr = new XMLHttpRequest();
              xhr.onload = () => {
                deffered.resolve(xhr.response);
              };

              xhr.onerror = () => {
                deferred.reject("Whoops");
              };
              xhr.open('GET', url);
              xhr.send();
              return deferred.promise;
            };

Promise libraries


ES2015: Native Promises

            // No more imports
            new Promise((resolve, reject) => { ... });

            // Methods
            Promise.prototype.then()
            Promise.prototype.catch()

            // Static methods
            Promise.all()
            Promise.race()
            Promise.reject()
            Promise.resolve()

So what?

    import Promise from 'bluebird';                       let getAjax = (url) => {
                                                            return new Promise(function (resolve, reject) {
    let getAjax = (url) => {                                  let xhr = new XMLHttpRequest;
      return new Promise(function (resolve, reject) {         xhr.addEventListener("error", reject);
        let xhr = new XMLHttpRequest;                         xhr.addEventListener("load", resolve);
        xhr.addEventListener("error", reject);                xhr.open("GET", url);
        xhr.addEventListener("load", resolve);                xhr.send();
        xhr.open("GET", url);                               )};
        xhr.send();                                       }
      });
    }

Objection 1 : Browser support bloat?


Size (gzipped):

            Bluebird       19.54KB
            es6-shim       13.92KB
            Q              5.01KB
            es6-promise    3.65KB

Objection 2 : Too simple?

            Promise.all()
            Promise.race()
            Promise.reject()
            Promise.resolve()

Race is amazing

  Promise.race()

Race is amazing

    let timer = new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('Timed out')), 5000)
    });

    Promise.race([
        fetch(`/user/${user_id}`),
        timer
    ])
    .then(successCallback)
    .catch(errorHandler);

Uploading

    Promise.race([
      fetch('//s3.amazonaws.com/us-west/0.png'),
      fetch('//s3.amazonaws.com/us-east/0.png'),
      fetch('//s3.amazonaws.com/europe/0.png'),
    ]).then((winner) => {
      console.log(`Uploading to: ${winner.url}`);
    })

Objection 3 : Swallow errors?

.done() or .finally()


Objection 3 : Swallow errors?

            $http.get('/url', config)
               .then(successCallback)
               .catch(errorHandler)
               .done(removeSpinner);

Just keep thenning

                fetch('/url')
                    .then(successCallback)
                    .catch(errorHandler)
                    .then(removeSpinner);

Objection 4 : Other libraries?

    $.ajax({ url: '/url', });

Objection 4 : Other libraries?

  // Bluebird's promisify()
  var request = Promise.promisify(require("request"));

  // Jquery's thenable
  $.ajax({ url: '/url', }).done(function() { ... });

Promise.resolve()

  Promise.resolve($.ajax(`/user/${user_id}`))
    .then(res => res.body)
    .then(console.log);

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