Async and Await Method tutorial in Advance JavaScript

 <!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Async Await Advance JavaScript</title>
    <link rel="stylesheet" href="">
</head>

<body>
    <script>
        //async function returns Promise
        //Example 1 :
        // async function test() {
        //     return "Hello";
        // }
        // test().then((result) => {
        //     console.log(result);
        // });

        //Example 2 :
        //await Method works inside async function as shown below :
        //If we use await Method without async function then Error will show.
        // async function testTwo() {
        //     console.log("2 : Message");
        //     await console.log("3 : Message");
        //     console.log("4 : Message");
        // }
        // console.log("1 : Message");
        // testTwo();
        // console.log("5 : Message");
        // console.log("6 : Message");

        //Example 3 :
        // async function test() {
        //     console.log("2 : Message");
        //     const response = await fetch("json/student_data.json");
        //     console.log("3 : Message");
        //     const students = await response.json();
        //     return students;
        // }
        // console.log("1 : Message");
        // let a = test();
        // console.log("4 : Message");
        // console.log(a);

        //Example 4 :
        // async function test() {
        //     const response = await fetch("json/student_data.json");
        //     const students = await response.json();
        //     return students;
        // }
        // let a = test();
        // console.log(a);

        //Example 5 :
        // async function test() {
        //     // const response = await fetch("json/student_data.json");
        //     // const students = await response.json();
        //     // return students;

        //     //We can write above three lines of Code in single line as shown below :
        //     return (await fetch("json/student_data.json")).json();
        // }
        // test().then((res) => {
        //     console.log(res);
        // }).catch((error) => {
        //     console.log(error);
        // });

        //Example 6 :
        async function test() {
            try {
                const response = await fetch("json/student_data.json");
                const students = await response.json();
                return students;
            }
            catch (error) {
                console.log(error);
            }
        }
        test().then((res) => {
            console.log(res);
        });
    </script>
</body>

</html>



Comments

Popular posts from this blog

Symbols tutorial in Advance JavaScript

String Methods in JavaScript