Difference between revisions of "JavaScript/C4/Promise-and-Async-Await-in-JS/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
(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...")
 
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 Start the '''Live server'''.
+
|| 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 '''console tab'''.
+
|| 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''' '''named as per your choice.
+
|| The '''parameters '''can be named as per your choice.
  
  
I have defined the first '''parameter''' as '''resolve '''- indicating the '''success state '''of '''promise.'''
+
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 '''- indicating the '''failure state '''of '''promise.'''
+
|| And, the second '''parameter''' is defined as '''reject ''' indicating the '''failure state '''of '''promise.'''
  
 
|-
 
|-
Line 225: Line 206:
  
  
You can give any '''variable names '''of your choice'''.'''
+
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 '''- as you know by default the '''promise '''will be in '''pending state.'''
+
|| 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 '''Browser'''
+
|| 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 '''undefined'''.
+
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 example'''.
+
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 .'''then method''' gets '''executed.'''
+
|| 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''' '''method''' gets '''executed'''.
+
|| If the '''state '''is '''rejected''', then the '''.catch method''' gets '''executed'''.
  
  
Line 465: Line 447:
  
 
|-
 
|-
|| Switch to '''Browser'''
+
|| Switch to '''browser'''
 
|| Switch back to the '''browser.'''
 
|| Switch back to the '''browser.'''
  
Line 478: Line 460:
  
  
As the '''state '''is '''fulfilled''',''' '''the '''.then method''' gets '''executed.'''
+
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'''.
 
|-
 
|| Switch to Editor
 
|| Switch back to the '''editor.'''
 
  
 
|-
 
|-
Line 651: Line 629:
  
 
|-
 
|-
|| Switch to '''Browser'''
+
|| 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''' '''method''' gets '''executed'''.
+
|| 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''' '''method''' in the chain gets executed.
+
|| Since the''' logA function''' is '''executed''' without errors, the next''' .then method''' in the chain gets executed.
  
  
Line 685: Line 663:
  
  
So '''logB''' '''function '''is '''executed''' and '''B''' is printed.
+
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, while '''executing''' the '''logCAndThrow function.'''
+
|| 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''' '''method''' will get '''executed'''.
+
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 '''instruction '''will''' '''be '''executed'''.
+
** Only after that the next instruction will be '''executed'''.
 
+
 
+
  
 
|-
 
|-
Line 836: Line 810:
  
 
return 1;
 
return 1;
|| Here, the '''function returns 1 '''this which is the''' '''value being '''returned'''.
+
|| 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''' '''method''' gets '''executed.'''
+
|| 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''' value'''.
+
The '''resolved promise '''will '''return My Data string''' as the value.
  
 
|-
 
|-
Line 981: Line 955:
  
  
So,''' '''it instructs the '''interpreter''' telling that inside this '''function '''some '''asynchronous calls''' are made.
+
So, it instructs the '''interpreter''' telling that inside this '''function '''some '''asynchronous calls''' are made.
  
 
|-
 
|-
Line 1,014: Line 988:
  
 
|-
 
|-
|| Switch to '''Browser'''
+
|| 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 '''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! '''
* Open the file '''MyPage.html''' in a web browser.
+
* Open the file '''MyPage.html''' in a '''web browser'''.
* Observe the output in the browser’s '''console'''
+
* 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


Visual Cue
Narration
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:
  • Promise
  • Chaining in Promises and
  • Async-Await in JS
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Visual Studio Code version 1.45.0 (code editor)
  • Firefox web browser

However you may use any other browser of your choice.

Slide : Pre-requisites To practice this tutorial,
  • You should be familiar with writing and executing JS files.
  • If not, please go through the prerequisite tutorials on this website.
Slide: Code files
  • The files used in this tutorial are available in the Code files link on this tutorial page.
  • Pls download and extract the file.
  • Make a copy and then use them for practising.
Slide: Promise The Promise object
  • represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Slide: Promise A Promise is always in one of these states:
  • pending: is the initial state, neither fulfilled nor rejected.
  • fulfilled: indicates that the operation was completed successfully.
    • So, .then() gets executed
  • rejected: indicates that the operation failed.
    • so, .catch() gets executed
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.


For this demonstration, I have already opened the same.


These files are available in the Code files link for practice.

[Editor] Type:


<!DOCTYPE html>

<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


Press: Alt + L and Alt + O

Save the file and start the Live server.
[Firefox] Press Ctrl + Shift + I


Point to the browser Console tab

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:


const p = new Promise(function (resolve, reject) {

setTimeout(() => {

resolve();

}, 2000);

});


console.log(p);


setTimeout(() => {

console.log(p);

}, 3000);

In the main.js file, replace the code as shown.
[Editor] Highlight:


const p = new Promise

Here, I have declared a Promise with new Context and assigned it to the promise variable.


Promise is a class in JS. c

[Editor] Highlight:


(function (resolve, reject) {

setTimeout(() => {

resolve();

}, 2000);

});

A Promise accepts a callback function.


The callback function accepts two parameters.

[Editor] Highlight:


resolve,

The parameters can be named as per your choice.


I have defined the first parameter as resolve indicating the success state of promise.

[Editor] Highlight:

reject

And, the second parameter is defined as reject indicating the failure state of promise.
[Editor] Highlight:


resolve, reject

Both the parameters are callback functions.


You can give any variable names of your choice.


Here, I’m using the standard variable names - resolve and reject.

[Editor] Highlight:


setTimeout(() => {

resolve();

}, 2000);

As mentioned, a promise always returns a state.


We usually make an API call using Promise.


But for now, I’m mocking the API call using setTimeout.

[Editor] Highlight: resolve(); As discussed, resolve and reject are callback functions.


Here I’m making a function call resolve() which will return a fulfilled state.

[Editor] Highlight: 2000 You already know that the setTimeout function accepts a second parameter in milliseconds.


Here, I’m passing 2000.


So, the callback function will be executed after 2 seconds.

Slide: Promise As discussed earlier the different states of a promise are mentioned here.


To verify them, I will be using console.log statements.

Switch to Editor Switch back to the editor.
[Editor] Highlight:


console.log(p);

I have initially printed the p value .

As you know by default the promise will be in pending state.


p value gets printed in the initial program execution.

[Editor] Highlight:

setTimeout(() => {

console.log(p);

}, 3000);

Here, I’m printing to see the state of the promise after 3 seconds.


This is because the setTimeout function executes the resolve function and returns success after 2 seconds.


So to verify the fulfilled state, I’m printing the promise after 3 seconds.

Press: Ctrl + S Save the file.
Switch to browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Promise { <state>: "pending" }

Here, we see the promise is initially pending.
Show 3 seconds delay.

(While recording)

[Browser] [Console Tab]:

Highlight:


Promise { <state>: "fulfilled", <value>: undefined }

If you have noticed here, the fulfilled state is printed after 3 seconds.


This is because after 2 seconds the setTimeout function returned success.


As I have not returned anything, the value is seen as Undefined.

Only Narration So far we have learnt about the basic concept of how promise works.


Now, let's take another example and understand the usage.

Switch to Editor Switch back to the editor.
[Editor] Type:


function onSuccess() {

console.log("Success!");

}


function onError() {

console.log("Error!");

}


const promise = new Promise(function (resolve, reject) {

setTimeout(() => {

resolve();

}, 2000);

});


promise.then(onSuccess);

promise.catch(onError);

In the main.js file, replace the code as shown.
[Editor] Highlight:


function onSuccess() {

console.log("Success!");

}


function onError() {

console.log("Error!");

}

Here, I have defined two functions onSuccess and onError.


The first will print ‘Success!’ on execution of onSuccess function.


The second will print ‘Error!’ on execution of onError function.


I’ll be using these functions in the promise example.

[Editor] Highlight:


const promise = new Promise(function (resolve, reject) {

setTimeout(() => {

resolve();

}, 2000);

});

Here, I have declared a similar promise, which resolves after 2 seconds.


As you are already aware, the promise variable will hold the returned state.

[Editor] Highlight:

promise.then(onSuccess);

So, here when the state is fulfilled, the .then method gets executed.


The .then method accepts a callback function.


So, I’m passing the onSuccess function as a parameter.


onSuccess function gets executed when the state is fulfilled.

[Editor] Highlight:


promise.catch(onError);

If the state is rejected, then the .catch method gets executed.


The .catch method accepts a callback function.


So, I’m passing onError function here.


onError function will get executed if the promise is rejected.

Press: Ctrl + S Save the file.
Switch to browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Success!

As the promise is resolved after 2 seconds, the state will be fulfilled.


As the state is fulfilled, the .then method gets executed.


The .then method has onSuccess function as a callback.


Hence the onSuccess function is executed and Success log is displayed here.

Only Narration Now let us take another example considering a scenario where we need to execute multiple functions.


To achieve this, we need to learn about chaining.

[Editor] Type:


function getPromise() {

return new Promise((resolve) => {

setTimeout(resolve, 2000);

});

}


function logA() {

console.log("A");

}


function logB() {

console.log("B");

}


function logCAndThrow() {

console.log("C");

throw new Error();

}


function catchError() {

console.log("Error!");

}


getPromise().then(logA).then(logB).then(logCAndThrow).catch(catchError);

In the main.js file, replace the code as shown.
[Editor] Highlight:


function getPromise() {

return new Promise((resolve) => {

setTimeout(resolve, 2000);

});

}

Here, I have declared a function which returns a Promise on its execution.
[Editor] Highlight:


return new Promise((resolve) => {

setTimeout(resolve, 2000);

});

The returned promise will resolve after 2 seconds.
[Editor] Highlight:


function logA() {

console.log("A");

}


function logB() {

console.log("B");

}


function logCAndThrow() {

console.log("C");

throw new Error();

}


function catchError() {

console.log("Error!");

}

Here, I have declared 4 different functions which just print on execution.
[Editor] Highlight:


throw new Error();

In the logCAndThrow function, I have thrown an error explicitly.


As the function rejects in the middle of execution, so the catch method gets executed.


Let’s see this.

[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:


.catch(catchError);

Then I execute the catchError function.


Now, let’s see how it works.

Press: Ctrl + S Save the file.
Switch to browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


A


Here, as the promise resolves to a fulfilled state, .then method gets executed.


We have passed the logA function in the first .then() method.


So log A function gets executed and prints A.

[Browser] [Console Tab]:

Highlight:


B

Since the logA function is executed without errors, the next .then method in the chain gets executed.


We have passed the logB function in the second .then() method.


So logB function is executed and B is printed.

[Browser] [Console Tab]:

Highlight:


C

Since the logB function is executed without errors, the next .then method in the chain gets executed.


We have passed the logCAndThrow function in the third .then() method.


So logCAndThrow function gets executed and C is printed.

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.


We will get an error, when the function is executed.

Switch to Browser Switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Error!

We got an error while executing the logCAndThrow function.


So, the .catch method gets executed.


We have passed the catchError function in the .catch method.


So, the catchError function is executed and Error! is printed.

Only Narration The advantages of chaining are
  • the code would be more modular and readable and
  • can have one proper error handling mechanism.
Switch to Editor Switch back to the editor.
[Editor] Highlight:


getPromise().then(logA).then(logB).then(logCAndThrow).catch(catchError);

Here, we have chained multiple function calls.


While executing this, we could encounter some error at run-time.


If so, the further .then execution will be stopped and .catch method will get executed.

Only Narration Now let’s learn about async-await.
Slide: Async - Await
  • async keyword - instructs the interpreter that there’s an asynchronous call happening inside the function.
  • async function always returns a Promise
  • await keyword
    • tells the interpreter to wait for the function to return.
    • Only after that the next instruction will be executed.
Only Narration Now, let us take an example and understand this better.
Switch to Editor Switch back to the editor.
[Editor] Type:


async function display() {

return 1;

}


console.log(display());


display()

.then(() => console.log("Promise is resolved!"))

.catch(() => console.log("Promise is rejected!"));

In the main.js file, replace the code as shown.
[Editor] Highlight:


async function display() {

return 1;

}

First, let's understand the basics of async function.


Here, I have declared a function display.

[Editor] Highlight:


async function

I’m using the async keyword besides the function keyword.


This tells the interpreter to consider this as an asynchronous function.

[Editor] Highlight:


return 1;

Here, the function returns 1 which is the value being returned.


The value is returned along with the state.

[Editor] Highlight:


console.log(display());

To verify the state and value, I have logged the function inside the console statement.
[Editor] Highlight:


display()

.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:


.then(() => console.log("Promise is resolved!"))

Here, in .then I have logged a message in the callback function.
[Editor] Highlight:


catch(() => console.log("Promise is rejected!"));

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:


Promise { <state>: "fulfilled", <value>: 1 }

If you see here, the state is fulfilled and the value is 1.


The value 1 is displayed here as the value returned from the function is 1.

[Browser] [Console Tab]:

Highlight:


Promise is resolved!

As the promise is in the fulfilled state, .then method gets executed.


It prints the message inside the .then callback function.


We have only learnt about the async keyword so far.


Now let’s learn about the await keyword.

Switch to Editor Switch back to the editor.
[Editor] Type:


const getData = () =>

new Promise(function (resolve, reject) {

setTimeout(() => {

resolve("My Data");

}, 2000);

});


async function display() {

const userData = await getData();

console.log(userData);

}


display();

In the main.js file, replace the code as shown.
[Editor] Highlight:


const getData = () =>

new Promise(function (resolve, reject) {

setTimeout(() => {

resolve("My Data");

}, 2000);

});

Here, I have declared a promise, which resolves after 2 seconds.


The resolved promise will return My Data string as the value.

[Editor] Highlight:


async function display() {

const userData = await getData();

console.log(userData);

}

Here, I have declared an async display function.


I have mentioned the async keyword beside function declaration.


So, it instructs the interpreter telling that inside this function some asynchronous calls are made.

[Editor] Highlight:


const userData = await getData();

Here, await keyword is used before the getData function call.


This is to tell the interpreter to wait until the getData function returns something.


The next instruction will be interpreted only after the getData function completes execution.

[Editor] Highlight:


console.log(userData);

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.


Then after 2 seconds, we see My Data displayed in the console.


The interpreter waited for the getData function to return something.


Only then it executes further instruction.

Only Narration With this we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • Promise
  • Chaining in Promises and
  • Async-Await in JS
Slide: Assignment As an assignment:
  • Open the file assignment.js which you have created earlier.
  • Clear the existing code.
  • Create a promise p
  • And resolve the promise after 2 seconds
  • Log ‘Promise is resolved!’ after the promise resolves.
  • Else, log Error!
  • Open the file MyPage.html in a web browser.
  • Observe the output in the browser’s console
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
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

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389