Intro to Promise API

The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never. it helps us to perform an async task by reducing the callback hell like a problem.

Syntax

new Promise( /* executor */ function(resolve, reject) { ... } );

Let say that if we have wanted to get the user from user id and then get their profile photo. In that case, we make two ajax call to server API and get data like this

function getUser(id, callback){
$.ajax({
method: 'get',
url:'/appi/user/'+id,
success: function(response){
callback(null, response);
},
fail : function(err) {
callback(err);
}
})
}
function getProfilePic(id, callback){
$.ajax({
method: 'get',
url:'/appi/profile/'+id,
success: function(response){
callback(null, response);
},
fail : function(err) {
callback(err);
}
})
}

// Get Complete User Detail
function getUserDetail(id.) {
getUser(id, function(err, response) {
if(err) throw err;
getProfilePic(id, function(err, picResponse) {
if(err) throw err;
// here you can get complete user detail
})
})
}

Here you can see these callback tree like structure, this is small, but in some case, you would require more data the synchronize fashion then callback tree getting large.These large callback trees are called as callback hells.
 To overcome these situations, we use promise. Promises are a way to write async code that still appears as though it is executing in a top-down way, and handles more types of errors due to encouraged use of styletry/catch error handling. Here how we solve above problem using promise.

function getUser(id) {
return new Promise(function (resolve, reject) {
$.ajax({
method: 'get',
url: '/appi/user/' + id,
success: resolve,
fail: reject
})
})
}
function getProfilePic(response) {
return new Promise(function (resolve, reject) {
$.ajax({
method: 'get',
url: '/appi/profile/' + response.id || response,
success: function (data) {
(response || {}).profilePic = data;
resolve(response);
},
fail: reject
})
});
}

function getUserDetail(id) {
getUser(id)
.then(getProfilePic)
.then(function (response) {
//here you get response
})
.catch(function (err) {
throw err;
});
}

you can see the difference in above the code, a code is compact and clean with respect to first one. That how promise helps us to perform an async task.

Originally published at www.codeatom.in on February 16, 2017.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.