JS Promise (Part 2 - Q.js, When.js and RSVP.js)

Venkat.R
5 min readDec 5, 2016

--

Promise Libraries

< Previous Article - JS Promise (Part 1 — Basics)

I would like to continue with an examination of JavaScript Promise API. Let’s have a look at Promise evolution by various libraries. below three libraries which we are going to explore on this article.

  1. Q.js Library
  2. When.js Library
  3. RSVP.js Library

Using q.js

The q.js is best one for promise implementation by Kris Kowal. It is more evident of promise evolution.

Lets have a look, What makes it special.

  • It provides two ways to define the promise. one is very famous by Q.defer() and another one is Q.Promise().
  • The Q.defer() method is custom and flexible way to define promise like defining anywhere in the code likevar deferred = Q.defer(); and any time that can be resolved, rejected and notified (deferred.resolve, deferred.reject, deferred.notify).
'use strict';// Defined the deferred.
var deferred = Q.defer();
// Resolving with Value.
deferred.resolve(responseText);
// Reject with Error Message.
deferred.reject(new Error("Status code was 400"));
// Notify during progress of promise.
deferred.notify(event.loaded / event.total);
// Return the Promise to be then-able
return deferred.promise;
  • The Q.Promise method helps to instantiate the Promise similar to native one.
// Using q.js Library.
var promise = Q.Promise(function(resolve, reject, notify) {
// succeed
resolve('value');
// or reject
// reject('error');
});
// Native Promise.
var myPromise = new Promise(function (resolve, reject) {
// Call resolve() method at the end of successful execution.
// Call reject() method for your failure case.});
  • There is third new parameter in Q.Promise() method called notify similarly third new callback in Q.then() called progressed.
  • Q.any is implemented like Promise.race It will return if any one of promise is get fulfilled in array of promises.
'use strict';Q.any(ArrayOfPromises)
.then(function (first) {
// Any of the promises was fulfilled.
}, function (error) {
// All of the promises were rejected.
});
  • .fail(func …) is implemented like Promise.catch. Its will catch the error which is thrown inside then method.
.then(onFulfillment, onRejection, onProgress)
.fail(function (error) {
// We get here with either foo's error or bar's error
});
  • .done(func …) method will trigger at the end.

That’s end of q.js library. below is the code for Basic, Serial and Parallel Samples.

Using When.js

This library is very similar to q.js and there is not much special things to mention other than Utility methods. It’s a stand-alone components of cujoJS (cujoJS is an architectural toolkit for building modular, maintainable web applications with zero framework lock-in).

Important to make a note, its been used by SystemJS Library (Universal dynamic module loader — loads ES6 modules, AMD, CommonJS).

Now its very easy to explain the similar methods rather having code pen.

// When.js Example.
var promise = when.promise(function(resolve, reject, notify) {
// Do some work, possibly asynchronously, and then
// resolve or reject.

// DEPRECATED: You can notify of progress events
// along the way if you want/need.

resolve(awesomeResult);
// or resolve(anotherPromise);
// or reject(nastyError);
});
// Then-able Method
promise
.delay(1000) // delay for 1 seconds.
.then(function() {
throw new CustomError('oops!');
})
.catch(CustomError, function(e) {
// Only catch CustomError instances
// all other types of errors will propagate automatically
})
.catch(function(e) {
// Catch other errors
})

Below is the when.js library source code defined public API. It helps to get fair idea about useful methods in when.js

// Few portion of when.js source code.// Create a pending promise
when.promise = promise;
// Create a resolved promise
when.resolve = Promise.resolve;
// Create a rejected promise
when.reject = Promise.reject;
// lift a function to return promises
when.lift = lift;
// call a function and return a promise
when['try'] = attempt;
// alias for when.try
when.attempt = attempt;
// Join 2 or more promises
when.join = join;
// Resolve a list of promises
when.all = all;
// Settle a list of promises
when.settle = settle;
// One-winner race
when.any = lift(Promise.any);
// Multi-winner race
when.some = lift(Promise.some);
// First-to-settle race
when.race = lift(Promise.race);
// Array.map() for promises
when.map = map;
// Array.filter() for promises
when.filter = filter;
// Array.reduce() for promises
when.reduce = lift(Promise.reduce);
// Array.reduceRight() for promises
when.reduceRight = lift(Promise.reduceRight);
// Is something promise-like, aka thenable
when.isPromiseLike = isPromiseLike;
// Promise constructor
when.Promise = Promise;
// Create a {promise, resolve, reject} tuple
when.defer = defer;

If you want to go through the when.js source code. click here

Using RSVP.js

It’s a lightweight library that provides tools for organising asynchronous code and tiny implementation of Promises/A+ as ES6 compliant and compatible with Task.js (experimental library for ES6 using Generators).

Lets have a look at the difference comparing with Native Promise API.

  • There is no Rejection Callback in then Method and it has only one parameter which is onFulfillment. The .catch() Method can be used to get the exceptions and rejections.
// Instantiation of RSVP Promise.
var rsvpPromise = new RSVP.Promise(function(resolve, reject) {
// succeed
resolve(value);
// or reject
reject(error);
});
// Then-able for Fulfillment and Catch is for Rejection.
rsvpPromise.then(function(value) {
// success
}).catch(function(error) {
// failure
});
  • There is no .race method Available (but .all is available for array of promise objects).
  • RSVP.hash() is for Objects properties values as Promises.
  • There is .finally() Method is available to execute at End.
// Object Properties of Promise.
var promises = {
"continent": getJSON("http:///...continent.json"),
"asia": getJSON("http:///...asia.json"),
"india": getJSON("http:///...india.json")
};
RSVP.hash(promises).then(function(response) {
// posts contains an array of results for the given promises
console.log(response.continent);
console.log(response.asia);
console.log(response.india);
})
.catch(function(reason) {
// if any of the promises fails.
})
.finally(function() {
console.log('The End !')
});
  • Custom Error events are available to invoke an Error. example: RSVP.on(‘error’).
  • You can listen to various events like created, chained, fulfilled, rejected like RSVP.on(‘created’, listener); that can be called for every Promise events.
// events
RSVP.on('created', listener);
RSVP.on('chained', listener);
RSVP.on('fulfilled', listener);
RSVP.on('rejected', listener);

So Quick, We are in the footer of this article. Last but not least. Have a look at HTML attribute defer for similar treatment.

HTML5 defer attribute

The defer attribute is something similar to promise for running your element after page load completes. It’s supported only for <script> element. soon we can expect for elements like img etc.

<script src="demo_defer.js" defer></script>

W3C Says, When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no “document.write” in javascript) and thus, the user agent can continue parsing and rendering.

Happy Reading, Stay tuned for my next article on jQuery and Angular Promise Implementation.

--

--

Venkat.R

👨‍💻 React, Full Stack Engineer | Father | Career Coach | Mentor | 📗 Blogger | Ex-Yahoo, Visa, Target, Proximus— webslate.io