Promises in JavaScript
Ahmed Mohamed
Posted on June 17, 2022
Introduction
Before ECMA Script 6 we were using Callback Functions to handle Asynchronous Operations.
What is Callback Function?
Callback Function is a function passed to another function to be invoked when the asynchronous operation completes.
setTimeout()
and setEnterval()
is an Example of Callback Functions.
To simplify Callback Function Definition, Let's take an example with the setTimeout()
Function.
//* Callback Function
function sayHello() {
console.log("Hello, World!");
}
setTimeout(sayHello, 1000);
Above Code, We used setTimeout()
Function that get another Function sayHello()
as a Parameter and then Executes it after a given Time 1 Second
, in This Example sayHello()
Function is the Callback Function Which was Executed after 1 Second.
So, the Above Example will Log "Hello, World!" in the Console after 1 Second.
Now after Understanding Callback Function Concept let's take a More Complicated Example on setTimeout()
Function.
setTimeout(() => {
console.log("I"); //* after (1) second
setTimeout(() => {
console.log("Love"); //* after (3) second
setTimeout(() => {
console.log("JavaScript"); //* after (6) second
setTimeout(() => {
console.log("Very"); //* after (10) second
setTimeout(() => {
console.log("Much"); //* after (15) second
setTimeout(() => {
console.log("!"); //* after (21) second
}, 6000);
}, 5000);
}, 4000);
}, 3000);
}, 2000);
}, 1000);
In the above example we used the setTimeout
Function a lot of Times to log "I Love JavaScript Very Much !" Sentence but every word after a special time.
But Did You Notice Things in This Example?
Yes Exactly The Code shape is Not Practical, It has 6 Callback Functions
, And in Large Scale Projects You will have More and More of these Nested Callback Functions
.
This Problem is Known as Callback Hell or Pyramid of Doom.
To Solve this Problem ES6 gets a new Object Called Promises.
To Understand the Promise Concept, Let Me and You, I give you a Promise that I Will Give You Your Book in the Next Week, This is Called a Promise.
Now, What is the possible instances of the promise I made to you?
Good, There is Two-State:
- I will give You Your Book and this is called Resolved State
- I will not Give You Your Book and this called Rejected State
- In Between Those two States, There is another State Called Pending State
Now Let's Take an Example of a Promise
const myPromise = new Promise((resolve, reject) => {
const connect = true;
if (connect) {
resolve("Your Connection Success :)");
} else {
reject(new Error("Sorry, Connection Failed :("));
}
});
myPromise
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("Process is Done :)");
});
In the above example, we use a Promise Object to handle a Connection Process.
We Notice that promise have three ways to Get data from It:
-
then()
Function to get Response in Resolved Case. -
catch()
Function to get Error in Rejected Case. -
finally()
Function Which Excuted in all Cases.
The Fantastic Thing in Promise is That you Can any Numbers of then()
Functions, Let's take an example:
//* Previous Code.....
myPromise
.then((res) => {
return res;
})
.then((res) => `${res} 1`)
.then((res) => `${res} 2`)
.then((res) => `${res} 3`)
.then((res) => `${res} 4`)
.then((res) => `${res} 5`)
.then((res) => console.log(res))
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("Process is Done :)");
});
In The Above Example the Result will be Like This in Console:
Your Connection Success :) 1 2 3 4 5
Process is Done :)
async
and await
Syntax
In ECMA Script 2017 We have a new Syntactical Suger to ease Promises Handling by using async
and await
Keywords.
So if we will write the Previous Example, It will be Like This:
const connectFunc = async () => {
try {
const res = await myPromise;
console.log(res);
} catch (error) {
console.log(error);
} finally {
console.log("Process is Done :)");
}
};
As We See, To use the async
Keyword and await
Method, we add async
before Function that will contain Promises Handling Code, and We use the await
Keyword before any Async Line, and Finally We put all of these in try-catch
block.
Conclusion
Finally, every day that passes by, there are new things that are added and other things that are Deprecated.
So, do not forget to follow all news in the field to develop yourself and your skills.
Posted on June 17, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.