JavaScript/C4/Promise-and-Async-Await-in-JS/English
Title of the script: Promise and Async-Await
Author: Jayesh Katta Ramalingaiah
Domain Reviewer:
Novice Reviewer:
Keywords: JavaScript, HTML, Promise, resolve, reject, pending, async, await
|
|
Slide: Title | Hello and welcome to the spoken tutorial on “Promise and Async-Await in JS”. |
Slide:
Learning Objectives |
In this tutorial, we will learn about:
|
Slide: System Specifications | This tutorial is recorded using:
However you may use any other browser of your choice. |
Slide : Pre-requisites | To practice this tutorial,
|
Slide: Code files |
|
Slide: Promise | The Promise object
|
Slide: Promise | A Promise is always in one of these states:
|
Only Narration | Now, let us take an example and understand this better. |
Show VS editor | Open Visual Studio Code editor. |
[Editor] Welcome Page -> Open Folder -> Practice-JS -> index.html & main.js
|
Then open the files index.html and main.js as explained in the earlier tutorials.
|
[Editor] Type:
<html lang="en"> <head> <title> Promise and Async-Await </title> </head> <body> <script src = "main.js" > </script> </body> </html> |
In the index.html file, replace the code as shown.
|
Press: Ctrl + S
|
Save the file and start the Live server. |
[Firefox] Press Ctrl + Shift + I
|
In the web browser, open the Browser developer tools panel and go to the Console tab. |
Switch to Editor | Switch back to the editor. |
[Editor] Type:
setTimeout(() => { resolve(); }, 2000); });
console.log(p); }, 3000); |
In the main.js file, replace the code as shown. |
[Editor] Highlight:
|
Here, I have declared a Promise with new Context and assigned it to the promise variable.
|
[Editor] Highlight:
setTimeout(() => { resolve(); }, 2000); }); |
A Promise accepts a callback function.
|
[Editor] Highlight:
|
The parameters can be named as per your choice.
|
[Editor] Highlight:
reject |
And, the second parameter is defined as reject indicating the failure state of promise. |
[Editor] Highlight:
|
Both the parameters are callback functions.
|
[Editor] Highlight:
resolve(); }, 2000); |
As mentioned, a promise always returns a state.
|
[Editor] Highlight: resolve(); | As discussed, resolve and reject are callback functions.
|
[Editor] Highlight: 2000 | You already know that the setTimeout function accepts a second parameter in milliseconds.
|
Slide: Promise | As discussed earlier the different states of a promise are mentioned here.
|
Switch to Editor | Switch back to the editor. |
[Editor] Highlight:
|
I have initially printed the p value .
As you know, by default, the promise will be in pending state.
|
[Editor] Highlight:
setTimeout(() => { console.log(p); }, 3000); |
Here, I’m printing to see the state of the promise after 3 seconds.
|
Press: Ctrl + S
Switch to Browser |
Save the file and switch back to the browser. |
Show 3 seconds delay.
(While recording) |
|
[Browser] [Console Tab]:
Highlight:
|
If you have noticed here, the fulfilled state is printed after 3 seconds.
|
Only Narration | So far we have learnt about the basic concept of how promise works.
|
Switch to Editor | Switch back to the editor. |
[Editor] Type:
console.log("Success!"); }
console.log("Error!"); }
setTimeout(() => { resolve(); }, 2000); });
promise.catch(onError); |
In the main.js file, replace the code as shown. |
[Editor] Highlight:
console.log("Success!"); }
console.log("Error!"); } |
Here, I have defined two functions - onSuccess and onError.
|
[Editor] Highlight:
setTimeout(() => { resolve(); }, 2000); }); |
Here, I have declared a similar promise, which resolves after 2 seconds.
|
[Editor] Highlight:
promise.then(onSuccess); |
So, here when the state is fulfilled, the .then method gets executed.
|
[Editor] Highlight:
|
If the state is rejected, then the .catch method gets executed.
|
Press: Ctrl + S
Switch to Browser |
Save the file and switch back to the browser. |
[Browser] [Console Tab]:
Highlight:
|
As the promise is resolved after 2 seconds, the state will be fulfilled.
|
Only Narration | Now let us take another example considering a scenario where we need to execute multiple functions.
|
[Editor] Type:
return new Promise((resolve) => { setTimeout(resolve, 2000); }); }
console.log("A"); }
console.log("B"); }
console.log("C"); throw new Error(); }
console.log("Error!"); }
|
In the main.js file, replace the code as shown. |
[Editor] Highlight:
return new Promise((resolve) => { setTimeout(resolve, 2000); }); } |
Here, I have declared a function which returns a Promise on its execution. |
[Editor] Highlight:
setTimeout(resolve, 2000); }); |
The returned promise will resolve after 2 seconds. |
[Editor] Highlight:
console.log("A"); }
console.log("B"); }
console.log("C"); throw new Error(); }
console.log("Error!"); } |
Here, I have declared 4 different functions which just print on execution. |
[Editor] Highlight:
|
In the logCAndThrow function, I have thrown an error explicitly.
|
[Editor] Highlight: getPromise() | Here, I make a getPromise function call and start chaining the rest of the methods. |
[Editor] Highlight: .then(logA) | Now I chain to execute the logA function. |
[Editor] Highlight: .then(logB) | Next I chain to execute the logB function. |
[Editor] Highlight:
.then(logCAndThrow) |
After this I chain to execute the logCAndThrow function. |
[Editor] Highlight:
|
Then I execute the catchError function.
|
Press: Ctrl + S
Switch to Browser |
Save the file and switch back to the browser. |
[Browser] [Console Tab]:
Highlight:
|
Here, as the promise resolves to a fulfilled state, .then method gets executed.
|
[Browser] [Console Tab]:
Highlight:
|
Since the logA function is executed without errors, the next .then method in the chain gets executed.
|
[Browser] [Console Tab]:
Highlight:
|
Since the logB function is executed without errors, the next .then method in the chain gets executed.
|
Switch to Editor | Switch back to the editor. |
[Editor] Highlight:
throw new Error(); |
As discussed earlier, we are explicitly throwing an error from the logCAndThrow function.
|
Switch to Browser | Switch back to the browser. |
[Browser] [Console Tab]:
Highlight:
|
We got an error while executing the logCAndThrow function.
|
Only Narration | The advantages of chaining are
|
Switch to Editor | Switch back to the editor. |
[Editor] Highlight:
|
Here, we have chained multiple function calls.
|
Only Narration | Next let’s learn about async-await. |
Slide: Async - Await |
|
Only Narration | Now, let us take an example and understand this better. |
[Editor] Type:
return 1; }
.then(() => console.log("Promise is resolved!")) .catch(() => console.log("Promise is rejected!")); |
In the main.js file, replace the code as shown. |
[Editor] Highlight:
return 1; } |
First, let's understand the basics of async function.
|
[Editor] Highlight:
|
I’m using the async keyword besides the function keyword.
|
[Editor] Highlight:
|
Here, the function returns 1 which is the value being returned.
|
[Editor] Highlight:
|
To verify the state and value, I have logged the function inside the console statement. |
[Editor] Highlight:
.then(() => console.log("Promise is resolved!")) .catch(() => console.log("Promise is rejected!")); |
Here, to verify the promise state, I have used .then and .catch methods. |
[Editor] Highlight:
|
Here, in .then I have logged a message in the callback function. |
[Editor] Highlight:
|
Similarly in .catch I have logged a message in the callback function. |
Press: Ctrl + S
Switch to Browser |
Save the file and switch back to the browser. |
[Browser] [Console Tab]:
Highlight:
|
If you see here, the state is fulfilled and the value is 1.
|
[Browser] [Console Tab]:
Highlight:
|
As the promise is in the fulfilled state, .then method gets executed.
|
[Editor] Type:
new Promise(function (resolve, reject) { setTimeout(() => { resolve("My Data"); }, 2000); });
const userData = await getData(); console.log(userData); }
|
In the main.js file, replace the code as shown. |
[Editor] Highlight:
new Promise(function (resolve, reject) { setTimeout(() => { resolve("My Data"); }, 2000); }); |
Here, I have declared a promise, which resolves after 2 seconds.
|
[Editor] Highlight:
const userData = await getData(); console.log(userData); } |
Here, I have declared an async display function.
|
[Editor] Highlight:
|
Here, await keyword is used before the getData function call.
|
[Editor] Highlight:
|
The returned data is stored in the userData variable.
To verify, I’m logging the variable. |
[Editor] Highlight:
display(); |
Here, I make a display function call to execute the display function. |
Press: Ctrl + S
Switch to Browser |
Save the file and switch back to the browser. |
Show 2 seconds delay in console.
(While recording) |
|
[Browser] [Console Tab]:
Highlight: My Data |
If you have noticed the delay, initially the console was empty.
|
Only Narration | With this we have come to the end of this tutorial.
|
Slide: Summary | In this tutorial, we have learnt:
|
Slide: Assignment | As an assignment:
|
Slide: About Spoken Tutorial Project |
|
Slide: Spoken tutorial workshops |
|
Slide: Forum questions | Pls post your timed queries in this forum |
Slide: Acknowledgement | Spoken Tutorial Project is funded by Ministry of Education (MoE), Government of India |
Slide: Thanks | The script for this tutorial is contributed by Jayesh and this is Praveen signing off. Thank you for joining |