Skip to content

Instantly share code, notes, and snippets.

@eoinkelly
Created December 16, 2016 02:32
Show Gist options
  • Save eoinkelly/8550f027932afc644f9c4787e4e164b7 to your computer and use it in GitHub Desktop.
Save eoinkelly/8550f027932afc644f9c4787e4e164b7 to your computer and use it in GitHub Desktop.

Promises

Good blog post on promises: https://developers.google.com/web/fundamentals/getting-started/primers/promises

  • A built-in part of the JS language since ES6
  • Native in most browsers now (except IE11 and older, Android 4.4 and older)
  • Available everywhere using JS implementation
  • http://caniuse.com/#search=promises

Why promises

  • Most JS frameworks uses them now
  • Ember uses them everywhere

What is a promise

  • an alternative to callbacks for managing asynchronous code

  • A Promise is a proxy for a value not necessarily known when the promise is created

  • A Promise is just a JS object which has a state in one of these states:

    • pending: initial state, not fulfilled or rejected.
    • fulfilled: meaning that the operation completed successfully.
    • rejected: meaning that the operation failed.

Scenario

Imagine we have a function which takes a long or unknown amount of time to complete. Using callbacks you so something like:

function getCurrentDistanceToMoon(success, fail) {
    let distance = calcMoonDistance(); // pings satellites, does complex math
    if(distance) {
        success(distance);
    } else {
        fail("The reason we failed to get distance");
    }
    // notice we don't actually return anything here
}

function displayDistanceToMoon(d) {
    $(".moon").html(d);
}

getCurrentDistanceToMoon(
  function(d) {
    console.log("The current distance to the moon is ", d);
    displayDistanceToMoon(d);
  },
  function(failureDescription) {
    console.log("We failed because: ", failureDescription);
  },
);

And this is the same thing done with promises:

function getCurrentDistanceToMoon() {
    return new Promise(function(resolve, reject) {
        let distance = calcMoonDistance(); // pings satellites, does complex math
        if(distance) {
            resolve(distance);
        } else {
            reject("The reason we failed to get distance");
        }
    });
}

function displayDistanceToMoon(d) {
    $(".moon").html(d);
}

getCurrentDistanceToMoon()
    .then(function(d) {
        console.log("The current distance to the moon is ", d);
    })
    .then(displayDistanceToMoon)
    .catch(function(failureDescription) {
        console.log("We failed because: ", failureDescription);
    });

Why are promises useful

  • Promises do the same stuff callbacks do except they are nicer in exchange for you having to understand them.
  • In simple examples callbacks work fine but if you have more steps in the chain then promises make things easier
  • They keep all the "control flow" (or "do this then that") code in one place
  • Flexible error handling
    • You can have unique error handling for each step in the chain
    • you can have a single catch that will gather errors that happen anywhere in the chain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment