JavaScript Promises

Everyone tried to promise something to someone. Maybe you promised your girlfriend to give her a call once your are on your way home.. Maybe you promised to respond to an event once you checked your calendar.. The common thing for both examples is that you are doing something where someone expects an answer once you are finished with whatever it is you need to do first. JavaScript Promises works somewhat the same way.
Let’s use the second example: You are asked if you can attend an event next Saturday. As a JavaScript Promise that would look like:
const rsvpToInvite = new Promise((resolve, reject) => { // Check of you can attend and then reply back });
You need to check your calendar before you can reply. It takes time. Finally you find that you are able to attend and you reply back with that. In a Promise that translates to calling the resolve()
function, in this case with a string:
const rsvpToInvite = new Promise((resolve, reject) => { // After checking your calendar, resolve with answer: resolve("I can attend the event"); });
If you instead found that you were unable to attend, you would answer the rsvp with a rejection:
const rsvpToInvite = new Promise((resolve, reject) => { // After checking your calendar, resolve with answer: reject("I can NOT attend the event"); });
To sum up: A Promise can do some work that takes time and then resolve()
or reject()
.
Now to the fundamental part of a Promise: The .then()
function:
const rsvpToInvite = new Promise((resolve, reject) => { resolve("I can attend the event"); // or: reject("I can NOT attend the event"); }); rsvpToInvite.then( (response) => console.log("Result:", response), (error) => console.log("Error:", error) );
then()
is called whenever you resolve()
or reject()
the Promise.
Full example:
const rsvpToInvite = new Promise((resolve, reject) => { setTimeout(() => { const iCanAttend = true; if (!iCanAttend) { reject("I can NOT attend the event"); } resolve("I can attend the event"); }, 1000); }); rsvpToInvite.then( (response) => console.log("Answer:", response), (error) => console.log("Error:", error) );
Note that I added a setTimeout()
with 1 second to the full example. That is to demonstrate that the then()
function is only called when the Promise is either resolved()
or rejected()
.
You can read more about promises on MDN and see more usage examples here.