Difference between revisions of "JavaScript/C4/Promise-and-Async-Await-in-JS/English"
Pravin1389 (Talk | contribs) |
Nancyvarkey (Talk | contribs) |
||
Line 53: | Line 53: | ||
|| Slide: Promise | || Slide: Promise | ||
|| The '''Promise object ''' | || The '''Promise object ''' | ||
− | * represents the eventual completion | + | * represents the eventual completion of an '''asynchronous operation '''and its resulting value. |
|- | |- | ||
Line 60: | Line 60: | ||
* '''pending''': is the initial state, neither fulfilled nor rejected. | * '''pending''': is the initial state, neither fulfilled nor rejected. | ||
* '''fulfilled''': indicates that the operation was completed successfully. | * '''fulfilled''': indicates that the operation was completed successfully. | ||
− | ** So, .'''then()''' gets '''executed''' | + | ** So, .'''then()''' method gets '''executed''' |
* '''rejected''': indicates that the operation failed. | * '''rejected''': indicates that the operation failed. | ||
− | ** | + | ** So, '''.catch()''' method gets '''executed''' |
|- | |- | ||
Line 70: | Line 70: | ||
|- | |- | ||
|| Show VS editor | || Show VS editor | ||
− | || Open '''Visual Studio Code editor''' | + | || Open '''Visual Studio Code editor'''. |
|- | |- | ||
Line 262: | Line 262: | ||
console.log(p); | console.log(p); | ||
|| I have initially printed the '''p value '''. | || I have initially printed the '''p value '''. | ||
− | As you know by default the '''promise '''will be in '''pending state.''' | + | As you know, by default, the '''promise '''will be in '''pending state.''' |
Line 308: | Line 308: | ||
− | As I have not '''returned''' anything, the value is seen as ''' | + | As I have not '''returned''' anything, the value is seen as '''undefined'''. |
|- | |- | ||
Line 371: | Line 371: | ||
} | } | ||
− | || Here, I have defined two '''functions onSuccess '''and '''onError.''' | + | || Here, I have defined two '''functions - onSuccess '''and '''onError.''' |
Line 575: | Line 575: | ||
throw new Error(); | throw new Error(); | ||
− | || In the '''logCAndThrow function''', I have '''thrown '''an | + | || In the '''logCAndThrow function''', I have '''thrown '''an '''error''' explicitly. |
Line 642: | Line 642: | ||
'''B''' | '''B''' | ||
− | || Since the''' logA function''' is '''executed''' without errors, the next''' .then method''' in the chain gets executed. | + | || Since the''' logA function''' is '''executed''' without '''errors''', the next''' .then method''' in the '''chain''' gets executed. |
Line 657: | Line 657: | ||
'''C''' | '''C''' | ||
− | || Since the '''logB function '''is executed without errors, the next '''.then method '''in the '''chain''' gets '''executed'''. | + | || Since the '''logB function '''is '''executed''' without '''errors''', the next '''.then method '''in the '''chain''' gets '''executed'''. |
Line 689: | Line 689: | ||
'''Error!''' | '''Error!''' | ||
− | || We got an error while '''executing''' the '''logCAndThrow function.''' | + | || We got an '''error''' while '''executing''' the '''logCAndThrow function.''' |
Line 698: | Line 698: | ||
− | So, the '''catchError function '''is executed and '''Error! '''is printed. | + | So, the '''catchError function '''is '''executed''' and '''Error! '''is printed. |
|- | |- | ||
Line 719: | Line 719: | ||
− | While '''executing''' this, we could encounter some error at '''run-time'''. | + | While '''executing''' this, we could encounter some '''error''' at '''run-time'''. |
Line 774: | Line 774: | ||
− | Here, I have '''declared''' a '''function | + | Here, I have '''declared''' a '''function display'''. |
|- | |- | ||
Line 853: | Line 853: | ||
'''Promise is resolved!''' | '''Promise is resolved!''' | ||
− | || As the''' promise '''is in the '''fulfilled | + | || As the''' promise '''is in the '''fulfilled state, .then method''' gets '''executed.''' |
Line 908: | Line 908: | ||
}); | }); | ||
− | || Here, I have '''declared''' a '''promise''', which '''resolves''' after 2 seconds. | + | || Here, I have '''declared''' a '''promise''', which '''resolves''' after '''2 seconds'''. |
Line 927: | Line 927: | ||
− | I have mentioned the '''async keyword '''beside '''function declaration.''' | + | I have mentioned the '''async keyword''' beside '''function declaration.''' |
Line 950: | Line 950: | ||
console.log(userData); | console.log(userData); | ||
− | || The '''returned data''' is stored in the '''userData variable ''' | + | || The '''returned data''' is stored in the '''userData variable'''. |
+ | |||
+ | To verify, I’m '''logging''' the '''variable'''. | ||
|- | |- | ||
Line 956: | Line 958: | ||
display(); | display(); | ||
− | || Here, I make a '''display function call''' to execute the '''display function'''. | + | || Here, I make a '''display function call''' to '''execute''' the '''display function'''. |
|- | |- | ||
Line 1,007: | Line 1,009: | ||
* Clear the existing code. | * Clear the existing code. | ||
* Create a '''promise p''' | * Create a '''promise p''' | ||
− | * And resolve the '''promise '''after 2 seconds | + | * And '''resolve''' the '''promise '''after 2 seconds |
* '''Log ‘Promise is resolved'''!’ after the '''promise resolves'''. | * '''Log ‘Promise is resolved'''!’ after the '''promise resolves'''. | ||
* Else, '''log Error! ''' | * Else, '''log Error! ''' |
Revision as of 11:10, 15 June 2021
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 |