× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JavaScript: Promises, Two Ways

Christoph Wagner
Apr 30, 2015
<p>Promises are becoming increasingly more popular as a practical and elegant way to handle asynchronicity in JavaScript. there are <a href="https://github.com/kriskowal/q">many</a> <a href="https://github.com/petkaantonov/bluebird/">promise</a> <a href="https://github.com/cujojs/when/">libaries</a> out there, and while they all fulfill the same basic goal of providing a solid and Promises/A+ compatible implementation, they differ slightly in the way you actually <em>create</em> a promise.</p> <p>For example, here's Bluebird:</p> <pre><code class="language-javascript">function ajaxGet(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest; xhr.addEventListener("error", reject); xhr.addEventListener("load", resolve); xhr.open("GET", url); xhr.send(null); }); }</code></pre> <p>This is the most standard-compatible way of creating a promise. But it's not the only viable one. For instance, here's the same function in Q:</p> <pre><code class="language-javascript">function ajaxGet(url) { var defer = q.defer(); var xhr = new XMLHttpRequest; xhr.addEventListener("error", defer.reject); xhr.addEventListener("load", defer.resolve); xhr.open("GET", url); xhr.send(null); return defer.promise; }</code></pre> <p>Different approach. Same result. In fact, Bluebird's <a href="https://github.com/petkaantonov/bluebird/blob/master/API.md">documentation</a> shows how to <a href="https://github.com/petkaantonov/bluebird/blob/master/API.md#deferred-migration">trivially construct a function like Q's <code>defer()</code> from its own <code>Promise</code> constructor</a>:</p> <pre><code class="language-javascript">function defer() { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); return { resolve: resolve, reject: reject, promise: promise }; }</code></pre> <p>So, which way is better? That's really up to you. Using the <code>Promise</code> constructor is the more standard-compatible way, but using Q's <code>defer()</code> syntax saves you one level of indentation, so there's that. In fact, when.js supports <a href="https://github.com/cujojs/when/blob/master/docs/api.md#whenpromise">both</a> <a href="https://github.com/cujojs/when/blob/master/docs/api.md#whendefer">ways</a>, although it does mark <code>defer()</code> as deprecated. </p> <p>If you'd like to learn more about promises, or how to efficiently manage asyncrhonicity in JavaScript, don't hesitate to send me a message or schedule a session.</p>
comments powered by Disqus