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

From Script | Spoken-Tutorial
Jump to: navigation, search
Line 290: Line 290:
 
|| Switch to '''browser'''
 
|| Switch to '''browser'''
 
|| Switch back to the '''browser.'''
 
|| Switch back to the '''browser.'''
 
|-
 
|| <nowiki>[Browser] [Console Tab]:</nowiki>
 
 
Highlight:
 
 
 
'''<nowiki>Promise { <state>: </nowiki>"pending" }'''
 
|| Here, we see the '''promise '''is initially '''pending'''.
 
  
 
|-
 
|-

Revision as of 21:02, 6 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


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