Difference between revisions of "JavaScript/C4/Promise-and-Async-Await-in-JS/English"
(Created page with "Title of the script: Promise and Async-Await Author: Jayesh Katta Ramalingaiah Domain Reviewer: Novice Reviewer: Keywords: JavaScript, HTML, Promise, resolve, reject, pe...") |
Nancyvarkey (Talk | contribs) |
||
Line 24: | Line 24: | ||
Learning Objectives | Learning Objectives | ||
|| In this tutorial, we will learn about: | || In this tutorial, we will learn about: | ||
− | |||
− | |||
* '''Promise''' | * '''Promise''' | ||
* '''Chaining in Promises''' and | * '''Chaining in Promises''' and | ||
* '''Async-Await '''in''' JS''' | * '''Async-Await '''in''' JS''' | ||
− | |||
− | |||
|- | |- | ||
|| Slide: System Specifications | || Slide: System Specifications | ||
|| This tutorial is recorded using: | || This tutorial is recorded using: | ||
− | |||
− | |||
* '''Ubuntu Linux''' OS version 18.04 | * '''Ubuntu Linux''' OS version 18.04 | ||
* '''Visual Studio Code''' version 1.45.0 ('''code editor''') | * '''Visual Studio Code''' version 1.45.0 ('''code editor''') | ||
Line 46: | Line 40: | ||
|| Slide : Pre-requisites | || Slide : Pre-requisites | ||
|| To practice this tutorial, | || To practice this tutorial, | ||
− | |||
− | |||
* You should be familiar with writing and executing''' JS''' files'''.''' | * You should be familiar with writing and executing''' JS''' files'''.''' | ||
* If not, please go through the prerequisite tutorials on this website. | * If not, please go through the prerequisite tutorials on this website. | ||
− | |||
− | |||
|- | |- | ||
Line 59: | Line 49: | ||
* Pls download and extract the file. | * Pls download and extract the file. | ||
* Make a copy and then use them for practising. | * Make a copy and then use them for practising. | ||
− | |||
− | |||
|- | |- | ||
|| Slide: Promise | || Slide: Promise | ||
|| The '''Promise object ''' | || The '''Promise object ''' | ||
− | |||
* represents the eventual completion (or failure) of an '''asynchronous operation '''and its resulting value. | * represents the eventual completion (or failure) of an '''asynchronous operation '''and its resulting value. | ||
− | |||
− | |||
|- | |- | ||
|| Slide: Promise | || Slide: Promise | ||
|| A '''Promise '''is always in one of these states: | || A '''Promise '''is always in one of these states: | ||
− | |||
− | |||
* '''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. | ||
Line 80: | Line 63: | ||
* '''rejected''': indicates that the operation failed. | * '''rejected''': indicates that the operation failed. | ||
** so, '''.catch()''' gets '''executed''' | ** so, '''.catch()''' gets '''executed''' | ||
− | |||
− | |||
|- | |- | ||
Line 135: | Line 116: | ||
Press: Alt + L and Alt + O | Press: Alt + L and Alt + O | ||
− | || Save the file and | + | || Save the file and start the '''Live server'''. |
|- | |- | ||
Line 142: | Line 123: | ||
Point to the browser '''Console''' tab | Point to the browser '''Console''' tab | ||
− | || In the web browser, open the '''Browser developer tools''' panel and go to the ''' | + | || In the '''web browser''', open the '''Browser developer tools''' panel and go to the '''Console tab'''. |
|- | |- | ||
Line 182: | Line 163: | ||
'''Promise '''is a '''class''' in '''JS.''' | '''Promise '''is a '''class''' in '''JS.''' | ||
− | + | c | |
|- | |- | ||
|| <nowiki>[Editor] Highlight:</nowiki> | || <nowiki>[Editor] Highlight:</nowiki> | ||
Line 206: | Line 187: | ||
resolve, | resolve, | ||
− | || The '''parameters '''can be | + | || The '''parameters '''can be named as per your choice. |
− | I have defined the first '''parameter''' as '''resolve ''' | + | I have defined the first '''parameter''' as '''resolve ''' indicating the '''success state '''of '''promise.''' |
|- | |- | ||
Line 215: | Line 196: | ||
reject | reject | ||
− | || And, the second '''parameter''' is defined as '''reject ''' | + | || And, the second '''parameter''' is defined as '''reject ''' indicating the '''failure state '''of '''promise.''' |
|- | |- | ||
Line 225: | Line 206: | ||
− | You can give any '''variable | + | You can give any '''variable''' names of your choice. |
Line 266: | Line 247: | ||
|- | |- | ||
|| Slide: Promise | || Slide: Promise | ||
− | || As discussed earlier the different states of a promise are mentioned here. | + | || As discussed earlier the different '''states''' of a '''promise''' are mentioned here. |
Line 280: | Line 261: | ||
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.''' | ||
Line 293: | Line 275: | ||
}, 3000); | }, 3000); | ||
− | || Here, I’m printing to see the state of the '''promise '''after '''3 seconds'''. | + | || Here, I’m printing to see the '''state''' of the '''promise '''after '''3 seconds'''. |
Line 306: | Line 288: | ||
|- | |- | ||
− | || Switch to ''' | + | || Switch to '''browser''' |
|| Switch back to the '''browser.''' | || Switch back to the '''browser.''' | ||
Line 337: | Line 319: | ||
− | As I have not '''returned''' anything, the value is seen as ''' | + | As I have not '''returned''' anything, the value is seen as '''Undefined'''. |
|- | |- | ||
Line 409: | Line 391: | ||
− | I’ll be using these '''functions '''in the '''promise | + | I’ll be using these '''functions '''in the '''promise''' example. |
|- | |- | ||
Line 433: | Line 415: | ||
promise.then(onSuccess); | promise.then(onSuccess); | ||
− | || So, here when the '''state '''is '''fulfilled''', the | + | || So, here when the '''state '''is '''fulfilled''', the '''.then method''' gets '''executed.''' |
Line 449: | Line 431: | ||
promise.catch(onError); | promise.catch(onError); | ||
− | || If the '''state '''is '''rejected''', then the '''.catch | + | || If the '''state '''is '''rejected''', then the '''.catch method''' gets '''executed'''. |
Line 465: | Line 447: | ||
|- | |- | ||
− | || Switch to ''' | + | || Switch to '''browser''' |
|| Switch back to the '''browser.''' | || Switch back to the '''browser.''' | ||
Line 478: | Line 460: | ||
− | As the '''state '''is '''fulfilled''', | + | As the '''state '''is '''fulfilled''', the '''.then method''' gets '''executed.''' |
Line 492: | Line 474: | ||
To achieve this, we need to learn about '''chaining'''. | To achieve this, we need to learn about '''chaining'''. | ||
− | |||
− | |||
− | |||
− | |||
|- | |- | ||
Line 651: | Line 629: | ||
|- | |- | ||
− | || Switch to ''' | + | || Switch to '''browser''' |
|| Switch back to the '''browser.''' | || Switch back to the '''browser.''' | ||
Line 664: | Line 642: | ||
− | || Here, as the '''promise resolves '''to a '''fulfilled state''', '''.then | + | || Here, as the '''promise resolves '''to a '''fulfilled state''', '''.then method''' gets '''executed'''. |
Line 679: | Line 657: | ||
'''B''' | '''B''' | ||
− | || Since the''' logA function''' is '''executed''' without errors, the next''' .then | + | || Since the''' logA function''' is '''executed''' without errors, the next''' .then method''' in the chain gets executed. |
Line 685: | Line 663: | ||
− | So '''logB | + | So '''logB function '''is '''executed''' and '''B''' is printed. |
|- | |- | ||
Line 694: | Line 672: | ||
'''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 726: | Line 704: | ||
'''Error!''' | '''Error!''' | ||
− | || We got an error | + | || We got an error while '''executing''' the '''logCAndThrow function.''' |
Line 743: | Line 721: | ||
* the code would be more modular and readable and | * the code would be more modular and readable and | ||
* can have one proper '''error handling mechanism'''. | * can have one proper '''error handling mechanism'''. | ||
− | |||
− | |||
|- | |- | ||
Line 761: | Line 737: | ||
− | If so, the further '''.then''' '''execution''' will be stopped and '''.catch | + | If so, the further '''.then''' '''execution''' will be stopped and '''.catch method''' will get '''executed'''. |
|- | |- | ||
Line 774: | Line 750: | ||
* '''await keyword ''' | * '''await keyword ''' | ||
** tells the '''interpreter '''to wait for the '''function '''to '''return.''' | ** tells the '''interpreter '''to wait for the '''function '''to '''return.''' | ||
− | ** Only after that the next | + | ** Only after that the next instruction will be '''executed'''. |
− | + | ||
− | + | ||
|- | |- | ||
Line 836: | Line 810: | ||
return 1; | return 1; | ||
− | || Here, the '''function returns 1 ''' | + | || Here, the '''function returns 1 ''' which is the value being '''returned'''. |
Line 900: | Line 874: | ||
'''Promise is resolved!''' | '''Promise is resolved!''' | ||
− | || As the''' promise '''is in the '''fulfilled '''state, '''.then | + | || As the''' promise '''is in the '''fulfilled '''state, '''.then method''' gets '''executed.''' |
Line 962: | Line 936: | ||
− | The '''resolved promise '''will '''return My Data string''' as the | + | The '''resolved promise '''will '''return My Data string''' as the value. |
|- | |- | ||
Line 981: | Line 955: | ||
− | So, | + | So, it instructs the '''interpreter''' telling that inside this '''function '''some '''asynchronous calls''' are made. |
|- | |- | ||
Line 1,014: | Line 988: | ||
|- | |- | ||
− | || Switch to ''' | + | || Switch to '''browser''' |
|| Switch back to the '''browser.''' | || Switch back to the '''browser.''' | ||
Line 1,029: | Line 1,003: | ||
'''My Data''' | '''My Data''' | ||
− | || If you have noticed the delay, initially the '''console '''was empty. | + | || If you have noticed the '''delay''', initially the '''console '''was empty. |
Line 1,050: | Line 1,024: | ||
|| Slide''': '''Summary''' ''' | || Slide''': '''Summary''' ''' | ||
|| In this tutorial, we have learnt: | || In this tutorial, we have learnt: | ||
− | |||
− | |||
* '''Promise''' | * '''Promise''' | ||
* '''Chaining in Promises''' and | * '''Chaining in Promises''' and | ||
* '''Async-Await '''in '''JS''' | * '''Async-Await '''in '''JS''' | ||
− | |||
− | |||
|- | |- | ||
|| Slide: Assignment | || Slide: Assignment | ||
|| As an assignment: | || As an assignment: | ||
− | |||
− | |||
* Open the file '''assignment.js''' which you have created earlier. | * Open the file '''assignment.js''' which you have created earlier. | ||
* Clear the existing code. | * Clear the existing code. | ||
* Create a '''promise p''' | * Create a '''promise p''' | ||
− | * And resolve the '''promise '''after | + | * And resolve the '''promise '''after 2 seconds |
− | * | + | * '''Log ‘Promise is resolved'''!’ after the '''promise resolves'''. |
− | * Else, | + | * Else, '''log Error! ''' |
− | * Open the file '''MyPage.html''' in a web browser. | + | * Open the file '''MyPage.html''' in a '''web browser'''. |
− | * Observe the output in the | + | * Observe the output in the '''browser’s console''' |
− | + | ||
− | + | ||
|- | |- | ||
Line 1,079: | Line 1,045: | ||
* The video at the following link summarises the Spoken Tutorial project. | * The video at the following link summarises the Spoken Tutorial project. | ||
* Please download and watch it | * Please download and watch it | ||
− | |||
− | |||
|- | |- | ||
Line 1,087: | Line 1,051: | ||
* We conduct workshops using spoken tutorials and give certificates. | * We conduct workshops using spoken tutorials and give certificates. | ||
* For more details, please write to us. | * For more details, please write to us. | ||
− | |||
− | |||
|- | |- |
Revision as of 16:31, 31 May 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 | Save the file. |
Switch to browser | Switch back to the browser. |
[Browser] [Console Tab]:
Highlight:
|
Here, we see the promise is initially pending. |
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 | Save the file. |
Switch to browser | 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 | Save the file. |
Switch to browser | 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 | Now let’s learn about async-await. |
Slide: Async - Await |
|
Only Narration | Now, let us take an example and understand this better. |
Switch to Editor | Switch back to the editor. |
[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 | Save the file. |
Switch to Browser | 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.
|
Switch to Editor | Switch back to the editor. |
[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 | Save the file. |
Switch to browser | 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 |