Image source
22 Jul 2014 - The Dark Side

Ambiguous Asynchronous Chaining With Promises

I have wasted hours understanding the subtlety of promises chaining. On that kind of “obvious once you know it problem” I think its worth sharing, not because I made a ground breaking discovery per se, but it can help you to get your “aha!” moment a bit earlier if you are new to promises.


What you should know

Promises let you organize asynchronous operations chaining like this.

var promise = asyncThatReturnPromise1();
promise.then(function() {
    return asyncThatReturnPromise2();
}).then(function() {
    return asyncThatReturnPromise3();
});

Which generates a succession of calls:

--- call1 --->|
              |--- call 2 --->|
                              |--- call 3 --->

The catch is that the promise returned by then() is not the initial one just returned for the purpose of chaining. Something you could expect from others library behavior like JQuery. It’s a brand new promise based on the return of the callback you have just defined.

Which means what could looks as the same code, will launch parallel some processing:

var promise = asyncThatReturnPromise1();
promise.then(function() {
    return asyncThatReturnPromise2();
});
promise.then(function() {
    return asyncThatReturnPromise3();
});
--- call1 -->|
             |--- call 2 ---->
             |--- call 3 -->

Test it by yourself

A few lines of CoffeeScript are on GitHub.

Conclusion

I would not blame the conception of this feature. To my opinion, it is the best way one can achieve the combination of sequenced and parallel in some standard way. I would just have liked to know this earlier, this left me with pretty weird first experience with promises.

tags: js promise

Fräntz Miccoli

This blog is wrapping my notes about software engineering and computer science. My main interests are architecture, quality and machine learning but content in this blog may diverge from time to time.

Since a bit of time now, I am the happy cofounder, COO & CTO of Nexvia.

Ideas are expressed here to be challenged.


About me Out Of The Comfort Zone Twitter