hello JS

A JavaScript community where you can learn and grow as a developer. Join helloJS, embrace JavaScript!

Follow publication

Promises are meant to be broken: Cancelable Promises in JS for all! (or at least everyone on our team)

Marc Cyr
hello JS
Published in
4 min readMar 29, 2017

--

Although this hits heavily on Promise Cancelation, this post is more about HOW it was accomplished rather than WHAT was accomplished (but resources for the WHAT are sufficiently linked). It’s about using higher-order functions/components to win big on Developer Experience.

Promises in the front-end are an awesome, if contentious, technology. For most front-end engineers writing modern web UIs, they are something that we are used to working with every day.

If you are an engineer using Promises, you know that despite the arguments against them, there are a lot of benefits in their use. I mention some of them here.

Still, with Promises there has always been one thing missing: cancelation. In approaches that currently exist, something has always been slightly missing. I wanted to see this:

This is what I see in Chrome when canceling a Promise. In Safari, you see a dash and no bytes transferred. Same effect.

We originally tried using RxJS to achieve this. What we found was that unsubscribing from an event stream in Rx did a very crucial thing: it meant nothing was “listening” to the data stream after the subscription was canceled. What it didn’t do: stop the browser from resolving the Promise.

Under the hood, we use Axios for promises. It’s proven to be an awesome library, with regular development as it moves toward v1.0. We found that the best way for us to implement it in a complex application was to abstract away the implementation details and give developers a simple requestHandler method to use. All they have to do is pass it an http method, url, success callback, and any additional options (including an option for a custom error handler if they don’t want to use the error handler requestHandler provides by default in the wrapped method).

This has been easy to understand for developers, and has been one of many things that aids our ability to develop new features quickly. Recently, we found it was time to upgrade to v0.15.3 and with that update came promise cancelation (as of 0.15.0, with some bug fixes on patch versions). The type of promise cancelation that gets the above view (canceled in the network tab). The benefits to such a feature depend on your particular use cases, and mileage may vary. For us, this is a game changer with regards to scalability.

--

--

Published in hello JS

A JavaScript community where you can learn and grow as a developer. Join helloJS, embrace JavaScript!

Written by Marc Cyr

Husband and father. Head of UI for Prisma Cloud at Palo Alto Networks running a large engineering team. Angel investor in Silicon Valley. https://20x.capital

No responses yet

Write a response