Blogger Ever

Something about Javascript Promises

A better way of handling the async functions and values. No more callbacks for handling or cuing the functions.

Javascript promises released in 2015, ES6. This is an standard technology released to cover up some core aspects of development when you need a good async function handling. These function says 'We are not done yet but we shall in future' and in return promises saves the day.

These concepts are not new, jQuery had deferred methods that are used before. However the support of Javascript promises is not wide but polyfills comes to rescue the older browsers.

Just a start...

Its better to start with a code.
// Using jQuery async function
var asyncFunction = $.getJSON('.../data.json');
asyncFunction.done(function (data) {
    // Do some magic here with data
The async functions have some strange behaviour, they do not return value instead we use callbacks for them. You can read the article I wrote about handling them. On the same day I got a comment on Google Plus about promises, but I wasn't interested in using them in production since bad...very bad browser support.

Browser Support

No Support
iOS Safari
Android Browser


An async function returns a promise to be completed in future. A promise could return with pending, means neither error nor success, second is success that simply do some function if function is completed successfully and final is error to handle pitfalls.

The code above was a basic example when async function is done successfully. The fail condition can be written as:
// Using jQuery async function
var asyncFunction = $.getJSON('.../data.json'); (data) {
    // handle the error here

There is one more method that can be called on async functions, either they success or fail using always.
// Using jQuery async function
var asyncFunction = $.getJSON('.../data.json');
asyncFunction.done(function (data) {
    // I will always return, no matter world exist
The promise object can let do some synchronous functions as well in different way.

var promise = new Promise(function (resolve, reject) {
promise.then(function () {
    // do something when doSomething() returns value
}).then(function () {
    // do something when above .then() is completed.

The above way will let you cue up the functions, either synchronous or a synchronous. 


The polyfill for promise is given by Taylor Hakes. The browser support is much better with IE 8, Safari 5+, iOS 4+.



2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.