Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Asynchronous Pipelines in Javascript with ES6 P...

Asynchronous Pipelines in Javascript with ES6 Promises

Danielle Brook-Roberge

July 30, 2015
Tweet

Transcript

  1. Introduction to Promises • A Promise is a value representing

    the result of an asynchronous process. • The Promise can either: – Resolve with the successful output of the process or – Reject with an error • A Promise is settled (resolved or rejected) exactly once. • Upon settlement, the Promise will call any registered callbacks.
  2. Promises in ES6 • The ES6 standard includes a Promise

    implementation. • Resolution callbacks are registered with the then() method. • Rejection callbacks are registered with the catch() method.
  3. Making Promises • ES6 provides a constructor to make a

    Promise directly. • With Promise.resolve() we can create a Promise that resolves immediately. • Promise.reject() returns a Promise that rejects immediately.
  4. Promise Chaining • The then() and catch() methods both return

    Promises, allowing callbacks to be chained. • Each Promise in the chain resolves to the return value of the previous callback, allowing the construction of a pipeline.
  5. Error Chaining • Return values from both resolution and rejection

    handlers resolve the next step in the chain. • We can reject instead by using throw instead of return, or by returning a Promise.reject().
  6. Promise Chaining Initial Promise then() Handler Handler catch() throw Resolves

    Rejects return throw return then() Handler throw Promise object Rejection Resolution
  7. Promise Flattening • If a Promise callback itself returns a

    Promise, it is inserted into the chain prior to the next handler. • This 'flattening' allows chains of asynchronous operations to occur without nesting.
  8. Promise Aggregation • We can wait for the completion of

    a set of promises with Promise.all() • The resulting promise will resolve if all the promises resolve. • It will reject if any of them reject.
  9. Inserting into the Pipeline • If we return a promise

    with handlers attached, they will be executed before the next handler in the chain. • This can be useful to adapt one API to another, for example.
  10. Asynchronous Recursion • Promise flattening can even be used recursively.

    • One application is to loop asynchronously over a series of HTTP requests. • In this way, we can control the end of the loop based on the contents of the requests.
  11. Other Implementations • The ES6 Promise specification is fairly bare-

    bones, but provides a useful baseline for this functionality going forward. • A more full-featured promise library is bluebird, which is available for browsers and for Node.js. • jQuery includes something called a Promise, but as it does not support chaining of return values it is not as useful.