Be the first user to complete this post
|
Add to List |
JavaScript Promises - Visualized
When you work with javascript, you will often find that callbacks are all over the place. They are in your front end code, in your middleware, and in case you use it to interface with your database, you would have it in your back end code too. Heck, they even come to haunt you in your dreams. One of the cleverest ways to avoid this hell is by using promises. Promises are a relatively new concept in javascript require you to think about your code in a slightly different, yet interesting way.
I recently had the opportunity to mess around with promises a lot. In this post, I will just touch upon some of ways I ended up using promises and provide those snippets for quick reuse. Look at the following visualization now, and then look at it again at the end of this post. It explains how the functions are associated when you create new promise obejcts. I am not going to go into detail of what promises are and its different use cases. You can always read this amazingly long article on html5rocks for that. However, if you dont have the time, this article should at least help you to address the matter at hand. So, how do you create a promise?var getData = new Promise(function(resolve, reject){
// Do something asynchronous and pass it a callback
getDataFromAMillionMilesAway(function(data){
if(data){
resolve(data);
}
else {
reject(new Error("Thats too far away"));
}
});
});
// And here's how you'd use it
getData().then(function(data){
console.log('Got Some Data! ', data);
});
getData().then(
function(data){
console.log('Got Some Data! ', data);
},
function(error){
console.log('Something really bad happened :( ', data);
}
);
var getData = function(config){
return new Promise(function(resolve, reject){
// Do something asynchronous and pass it a callback
getDataFromAMillionMilesAway(config, function(data){
if(data){
resolve(data);
}
else {
reject(new Error("Thats too far away"));
}
});
});
}
getData(config1)
.then(function () {
return getData(config2);
})
.then(function () {
return getData(config3);
})
.then(function(){
console.log('All the data was fetched sequentially.');
});
getData(config).then(function(data){
data = _.extend({}, data, {'key','valye'});
return data;
}).then(function(modifiedData){
console.log(modifiedData);
});
getData(config)
.then(function(data){
return JSON.parse(data);
})
.then(function(parsedData){
console.log(parsedData);
});
//is equivalent to
getData(config)
.then(JSON.parse)
.then(function(parsedData){
console.log(parsedData);
});
Also Read:
- position: relative
- A simple requestAnimationFrame example visually explained
- window.onload vs document.onload
- window vs document
- css - align text to an image vertically