Hi folks, as we all know today is kiss day (the exciting day , isn't it). So today I went to my lover JS (JavaScript) and asked for a kiss. But as you know What I did, on promise day, I just rejected my necklace promise which I had given to my lover Js and enjoyed the dinner date with her. Oh ! you haven't read that story, don't worry here is the link, you can checkout since before knowing async-await ,you must know promises. devkeycode.hashnode.dev/promise-day-feb-11t..
Coming back to today , so since that day I reject the promise , so today when I asked for a kiss , my lover js told me that you first resolved/fullfiled your promise , then only ask for a kiss and if she like the necklace then she would give me a kiss otherwise she will reject this time. So, I have written code in this way.
//This function named myPromiseToJs will return a Promise object
function myPromiseToJs() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
setTimeout(() => {
let isBoughtNecklace = true;
// let isBoughtNecklace = false;
if (isBoughtNecklace) {
resolve("Hey Js , here is your necklace.");
} else {
reject(
"Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
);
}
}, 2000);
});
}
//This function named jsPromiseToMe will return a Promise object
function jsPromiseToMe() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
// let isNecklaceLiked = true;
let isNecklaceLiked = false;
setTimeout(() => {
if (isNecklaceLiked) {
resolve(
"Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised."
);
} else {
reject("Sorry honey , I didn't like the necklace so no kisses.");
}
}, 2000);
});
}
//calling myPromiseToJs
myPromiseToJs()
.then((myMessage) => {
console.log(myMessage);
})
.catch((anyIssueOccurMessage) => {
console.log(anyIssueOccurMessage);
});
//later calling jsPromiseToMe
jsPromiseToMe()
.then((jsMessage) => {
console.log(jsMessage);
})
.catch((anyIssueOccurMessage) => {
console.log(anyIssueOccurMessage);
});
Output will be -
Hey Js , here is your necklace. Sorry honey , I didn't like the necklace so no kisses.
Though it showing the code is working but its not correct way . Since as you know js told me that first you resolve your promise then only I will give you a promise. So if I just call the function myPromiseToJs() and jsPromiseToMe() like this , then its not confirmed that I would get the required results since here it depends on milliseconds we defined inside the setTimeout(and we know that the setTimeout() method calls a function after a number of milliseconds). So order of execution can be differ depending on the milliseconds we defined in each setTimeout function. jsPromiseToMe function can be invoked before myPromiseToJs function if we change the number of milliseconds inside the myPromiseToJs function from 2000 to 4000 miiliseconds. But that will break the whole logic , since js already told she will give promise only when my promise is resolved.
You didn't believe me that how the logic will be break . Here the code whose output is entirely different which we didn't expect. The wrong code is written here .
function myPromiseToJs() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
setTimeout(() => {
let isBoughtNecklace = true;
// let isBoughtNecklace = false;
if (isBoughtNecklace) {
resolve("Hey Js , here is your necklace.");
} else {
reject(
"Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
);
}
}, 4000);
});
}
function jsPromiseToMe() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
// let isNecklaceLiked = true;
let isNecklaceLiked = false;
setTimeout(() => {
if (isNecklaceLiked) {
resolve(
"Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised."
);
} else {
reject("Sorry honey , I didn't like the necklace so no kisses.");
}
}, 2000);
});
}
myPromiseToJs()
.then((myMessage) => {
console.log(myMessage);
})
.catch((anyIssueOccurMessage) => {
console.log(anyIssueOccurMessage);
});
jsPromiseToMe()
.then((jsMessage) => {
console.log(jsMessage);
})
.catch((anyIssueOccurMessage) => {
console.log(anyIssueOccurMessage);
});
Output will be -
Sorry honey , I didn't like the necklace so no kisses. Hey Js , here is your necklace.
Here the output is totally wrong. It's making the whole logic wrong, since who rejects the necklace even before seeing it. Is n't it ?
Also in real life , we can't decide how much time it will take to get response back from the server against the request we have sended to the server for fetching some resource , so instead of executing the function one after the other in this way , we will use then and catch block and use promsie chaining and this will restrict jsPromiseToMe function to be invoked/called only when myPromiseToJs function returned promise is resolved.
Returning promises from another promises allows us to build chains of asynchronous actions. Since promises can create chains to handle multiple dependent asynchronous operations and since jsPromiseToMe and myPromiseToJs both are asynchronous operations and jsPromiseToMe depends on myPromiseToJs (since jsPromiseToMe must only be called if myPromiseToJs is fullfilled/resolved)
We can chain multiple promises. Also note that in promise chaining, if any promise in the chain rejects, then the resolving flow jumps to the first .catch(), bypassing all .then() in between (somewhat like continue did in the loops , it will not go further code execution in that specific iteration , but there it will go to next iteration but here it will left/bypass all the followings then block and jumps to first catch block.)
function myPromiseToJs() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
setTimeout(() => {
let isBoughtNecklace = true;
// let isBoughtNecklace = false;
if (isBoughtNecklace) {
resolve("Hey Js , here is your necklace.");
} else {
reject(
"Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
);
}
}, 4000);
});
}
function jsPromiseToMe() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
// let isNecklaceLiked = true;
let isNecklaceLiked = false;
setTimeout(() => {
if (isNecklaceLiked) {
resolve(
"Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised."
);
} else {
reject("Sorry honey , I didn't like the necklace so no kisses.");
}
}, 2000);
});
}
//here using Promise chaining
myPromiseToJs()
.then((myMessage) => {
console.log(myMessage);
return jsPromiseToMe(); //returning another promise object form here
})
.then((jsMessage) => {
console.log(jsMessage);
})
.catch((anyIssueOccurMessage) => {
console.log(anyIssueOccurMessage);
});
Output will be -
Hey Js , here is your necklace. Sorry honey , I didn't like the necklace so no kisses.
But you see since we just have 2 dependent asynchronous operations here , but what if there are so many asynchronous dependent operations will be there that have to execute one after the another but only if previous one promise in the promise chain is done. So for that the chain will be huge.
So to avoid chain of promises (just for readability) a new feature "async await" had introduced. Javascript added support for async/await in 2017 as part of ECMAScript 2017 JavaScript edition.
"async/await is just a syntactic sugar on top of promises." The same logic we can write using async await in this way-
function myPromiseToJs() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
setTimeout(() => {
let isBoughtNecklace = true;
// let isBoughtNecklace = false;
if (isBoughtNecklace) {
resolve("Hey Js , here is your necklace.");
} else {
reject(
"Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
);
}
}, 4000);
});
}
function jsPromiseToMe() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
// let isNecklaceLiked = true;
let isNecklaceLiked = false;
setTimeout(() => {
if (isNecklaceLiked) {
resolve(
"Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised."
);
} else {
reject("Sorry honey , I didn't like the necklace so no kisses.");
}
}, 2000);
});
}
//A function named runMyKissDay introduced and I prefixed the function definition with a keyword "async"
async function runMyKissDay() {
try {
const myMessage = await myPromiseToJs();
console.log(myMessage);
const jsMessage = await jsPromiseToMe();
console.log(jsMessage);
} catch (errMessage) {
console.log(errMessage);
}
}
runMyKissDay();
Output will be the same -
Hey Js , here is your necklace. Sorry honey , I didn't like the necklace so no kisses.
Inside the runMyKissDay function ,I prefixed the "await" keyword in the function invocation of myPromiseToJs() ,this means that the code execution will not go further inside this runMyKissDay function until myPromiseToJs function which internally returns a promise object can either be resolved/fullfilled or rejected the promise and hence preventing the jsPromiseToMe function to be executed before myPromiseToJs function execution and thus handling the multiple dependent asynchronous operations even without doing promise chaining which can be difficult to manage and understand too.
So since you understand the async await better , let's once again run the code in success of your understanding.
function myPromiseToJs() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
setTimeout(() => {
let isBoughtNecklace = true;
// let isBoughtNecklace = false;
if (isBoughtNecklace) {
resolve("Hey Js , here is your necklace.");
} else {
reject(
"Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
);
}
}, 4000);
});
}
function jsPromiseToMe() {
return new Promise(function (resolve, reject) {
//to bring async behaviour using setTimeout so this promise execution will take sometime
let isNecklaceLiked = true;
// let isNecklaceLiked = false;
setTimeout(() => {
if (isNecklaceLiked) {
resolve(
"Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised."
);
} else {
reject("Sorry honey , I didn't like the necklace so no kisses.");
}
}, 2000);
});
}
async function runMyKissDay() {
try {
const myMessage = await myPromiseToJs();
console.log(myMessage);
const jsMessage = await jsPromiseToMe();
console.log(jsMessage);
} catch (errMessage) {
console.log(errMessage);
}
}
runMyKissDay();
Output will be -
Hey Js , here is your necklace. Hey honey! ,Come here.I really liked your necklace. Thankyou for the necklace and here's your kiss as promised.
Hey , you see I got the kiss , this time. Now happily I can sleep ,thanks for your understanding. And wait, You know tomorrow is Valentine's Day (big day) and since I have given this valentine week dedicated to my lover Js(JavaScript) so I have written articles related to her on each day. You can checkout all the articles here - devkeycode.hashnode.dev