About

Labels

slider

Recent

Navigation

Something about Javascript Promises


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

IE
No Support
Chrome
43
Edge
12
Firefox
38
Opera
31
Safari
8
iOS Safari
8.4
Android Browser
4.4.4

Promise

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');
asyncFunction.fail(function (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) {
doSomething();
});
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. 

Polyfill

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

References

Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: