Javascript Promises Explained
Intro
As of ES6, Promises are native to Javascript. But what are they and why are they helpful?
Javascript promises are powerful tools for dealing with asynchronous calls. If you have ever written any javascript that called for using callbacks, you may have had to deal with nested callbacks (callback hell).
Everything you can do with promises you can do with callbacks, but the way you can structure then, and write them, makes it a lot easier to follow, debug, and deal with. They basically allow you to write asynchronous code that looks like synchronous code.
Relevant Definitions
Promises (As per Javascript): A promise is an object that is used in asynchronous Javascript. It represents a value which may be available now, or in the future, or never.
Asynchronous: NOT happening at the same time.
In programming, asynchronous is something that runs in parallel. It is a piece of code that runs separately from the main program thread and notifies the main thread when it is completed
Callback: Any piece of executable code that is passed as an argument to other code. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
Common Use Cases
Backend (Nodejs): Nodejs is not much more than a big event loop waiting for a callback. It is virtually impossible to write any node without using callbacks. Promises can be used for anything and everything. This includes file reading, database interactions (reading/writing), I/O and many other operations.
Front end: Ajax calls. There are others, but this is the biggest use case in my estimation.
Stages Of A Promise
Pending - The promise has not fulfilled or rejected
Resolved - The action has succeeded
Rejected - The action failed
After instantiating a promise object, you then get two methods to decide what to do next after the task is complete
then() - Do some async stuff
catch() - catch potential errors (to return as rejected)
Promise Example In English - The Car Loan Example
Imagine you are going to buy a car but do not have the money in your bank account. You go to the bank and request a loan. The bank will not just hand over money until you purchase that car but they do promise to give you the money at the point of purchase.
Consider the stages of a promise mentioned above and how they fit this example
Pending: The bank has agreed it will give money for the purchase.
Resolved: You purchased the car and the bank give you the money.
Rejected: You decided not to purchase a car so the promise has been rejected.
Setup A Promise
For example:
Potential Negatives
One potential negative of Promises is that they run until completion. That may cause a scenario where clicks on a link to bring up a page. That page may trigger an Ajax call that was done inside of a promise. Before the call is completed the user clicks off of the page and does not care about the result.
There was a TC39 proposal to add the ability to cancel promises but that has since been withdrawn. Read here for more details on that action.
As of ES6, Promises are native to Javascript. But what are they and why are they helpful?
Javascript promises are powerful tools for dealing with asynchronous calls. If you have ever written any javascript that called for using callbacks, you may have had to deal with nested callbacks (callback hell).
Everything you can do with promises you can do with callbacks, but the way you can structure then, and write them, makes it a lot easier to follow, debug, and deal with. They basically allow you to write asynchronous code that looks like synchronous code.
Relevant Definitions
Promises (As per Javascript): A promise is an object that is used in asynchronous Javascript. It represents a value which may be available now, or in the future, or never.
Asynchronous: NOT happening at the same time.
In programming, asynchronous is something that runs in parallel. It is a piece of code that runs separately from the main program thread and notifies the main thread when it is completed
Callback: Any piece of executable code that is passed as an argument to other code. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
Common Use Cases
Backend (Nodejs): Nodejs is not much more than a big event loop waiting for a callback. It is virtually impossible to write any node without using callbacks. Promises can be used for anything and everything. This includes file reading, database interactions (reading/writing), I/O and many other operations.
Front end: Ajax calls. There are others, but this is the biggest use case in my estimation.
Stages Of A Promise
Pending - The promise has not fulfilled or rejected
Resolved - The action has succeeded
Rejected - The action failed
After instantiating a promise object, you then get two methods to decide what to do next after the task is complete
then() - Do some async stuff
catch() - catch potential errors (to return as rejected)
Promise Example In English - The Car Loan Example
Imagine you are going to buy a car but do not have the money in your bank account. You go to the bank and request a loan. The bank will not just hand over money until you purchase that car but they do promise to give you the money at the point of purchase.
Consider the stages of a promise mentioned above and how they fit this example
Pending: The bank has agreed it will give money for the purchase.
Resolved: You purchased the car and the bank give you the money.
Rejected: You decided not to purchase a car so the promise has been rejected.
Setup A Promise
let promise = new Promise(function(resolve, reject) {
// Request a loan
if (/* Loan was approved */) {
resolve("It worked, buy the car, give the money");
}
else {
reject(Error("Loan did not come though, reject transaction"));
}
});
** The promise from the bank is not the value itself, but rather, the promise of a value.
Consume The Promise
promise.then(function(result) {
console.log(result); // It worked
}, function(err) {
console.log(err); // Error
});
You can also chain promises together. For example:
get_loan()
.then(function() { test drive Honda civic .... return second_promise(): })
.then(function() { test drive Honda Accord .... return third_promise(): })
.then(function() { buy a car })
.catch( error case - do not like either car or not enough money even with the loan)
Potential Negatives
One potential negative of Promises is that they run until completion. That may cause a scenario where clicks on a link to bring up a page. That page may trigger an Ajax call that was done inside of a promise. Before the call is completed the user clicks off of the page and does not care about the result.
There was a TC39 proposal to add the ability to cancel promises but that has since been withdrawn. Read here for more details on that action.
great
ReplyDeleteMan, I couldn't had figured out with them for like a week, and then here you comes with that summary, thanks a lot! As you may have suggested, I'm new to javascript at all, have just started a month ago. So far as programming language, I had no experience on that before as well. And, given the experience I got so far, I would say for sure that javascript is the best option to start making things out with coding. It may seems to be pretty hard for the first time, but just in month later you'll be able to write some tricky script like this one of a game of the javascript snake https://explainjava.com/snake-game/ Of course, this is not the perfect limit - at least I know a guy who wrote the real pacman with js :)
ReplyDelete