*PROMISE, ASYNC & AWAIT *


Q1: Write one example explaining how you can write a callback function.

ANS :-

                function calculate(num1, num2){
                    return num1 * num2
                }
                
                function displayDate(name, age){
                    console.log(`${name} : age is ${age}`)
                }
                
                displayDate("Nitin", calculate(19,1));
            

OUTPUT :-


Q2: Write a callback function to print numbers from 1 to 7, in which 1 should be printed after 1 sec, 2 should be printed after 2 sec, 3 should be printed after 3 sec, and so on.
Explain callback hell.
Numbers
1
2
3
4
5
6
7

ANS :-

                setTimeout(()=>{
                    console.log("1")
                    setTimeout(()=>{
                        console.log("2")
                        setTimeout(()=>{
                            console.log("3");
                            setTimeout(()=>{
                                console.log("4");
                                setTimeout(()=>{
                                    console.log("5");
                                    setTimeout(()=>{
                                        console.log("6");
                                        setTimeout(()=>{
                                            console.log("7")
                                        },7000)
                                    },6000)
                                },5000)
                            },4000)
                        },3000)
                    },2000)
                },1000)
            

OUTPUT :-


Q1: "Write the promise function to print numbers from 1 to 7, in which 1 should be printed after 1 sec, 2 should be printed after 2 sec, 3 should be printed after 3 sec, and so on.
Numbers
1
2
3
4
5
6
7

                let ans3 = document.getElementById("ans3")
                function promiseChain(alpha, timeout){
                    return new Promise((res, rej)=>{
                        setTimeout(()=>{
                            console.log(alpha);
                            res("This promise is resolved !!!....")
                        },timeout);
                    })
                }
                function visible(){
                    promiseChain("1",1000)
                    .then(()=>promiseChain("2", 2000))
                    .then(()=>promiseChain("3", 3000))
                    .then(()=>promiseChain("4", 4000))
                    .then(()=>promiseChain("5", 5000))
                    .then(()=>promiseChain("6", 6000))
                    .then(()=>promiseChain("7", 7000))
                }
                visible();
            

OUTPUT :-


Q4: Create a promise function accepting an argument, if yes is passed to the function then it should go to resolved state and print Promise Resolved, and if nothing is passed then it should go to reject the state and catch the error and print Promise Rejected

ANS :-

                let variable = true 
                function promiseFun(){
                    return new Promise((resolve,reject)=>{
                        if(variable === true){
                            resolve("Promise resolve succesfully....")
                        }
                        else{
                            reject(Error("Promise rejected !!!"))
                        }
                    })
                }
                
                promiseFun(variable).then((date)=>{
                    console.log(date)
                }).catch((err)=>{
                    console.log(err)
                })
            

OUTPUT :-


Q5: Create examples to explain callback function

ANS :-

#A callback function is a function passed to another function as an argument. Callbacks promote asynchronous programming



                function divide(num1, num2, callback) {
                    let output = num1 / num2;
                    callback(output);
                    }
                          
                    function division(output) {
                    console.log('The result is: ' + output);
                    }
                          
                divide(100, 100,  division);
            

OUTPUT :-


Q6: Create examples to explain callback hell function

ANS:-

The phenomenon which happens when we nest multiple callbacks within a function is called a callback hell. The shape of the resulting code structure resembles a pyramid and hence callback hell is also called the “pyramid of the doom”. It makes the code very difficult to understand and maintain.




                setTimeout(()=>{
                    console.log("1")
                    setTimeout(()=>{
                        console.log("2")
                        setTimeout(()=>{
                            console.log("3");
                            setTimeout(()=>{
                                console.log("4");
                                setTimeout(()=>{
                                    console.log("5");
                                    setTimeout(()=>{
                                        console.log("6");
                                        setTimeout(()=>{
                                            console.log("7")
                                        },7000)
                                    },6000)
                                },5000)
                            },4000)
                        },3000)
                    },2000)
                },1000)   
            

OUTPUT :-


Q7 :Create examples to explain promises function

ANS :-

Promise Function are the functions that return a promise object. A promise is an object which represents the completion or failure of an asynchronous operation along with its result. They come with in-built error handling. Here inside the findSum() function, promise object "pr" has been created. Then the function is called and ".then" block is attached to handle the resolved part and ".catch" handles the reject part.



                function findSum(num1,num2){
                    let pr = new Promise(function(res,rej){
                        setTimeout(function(){
                            let sum = num1 + num2;
                            if(isNaN(sum))
                            {
                                rej("Try Again! Enter a valid number");
                            }
                            else
                            {
                                res(sum);
                            }
                        }, 2000)
                    })
                    return pr;
                }
                
                findSum(26,23).then(function(ans){
                    console.log("Sum =", ans);
                }).catch(function(err){
                    console.log(err);
                })
            

OUTPUT :-


Q8: Create examples to explain async await function

ANS :-

                function fetchData() {
                    return new Promise(resolve => {
                      setTimeout(() => resolve('Data received!'), 2000);
                    });
                  }
                  
                  async function printData() {
                    console.log("Fetching data...");
                    const data = await fetchData();
                    console.log(data);
                  }
                  
                  printData();
            

OUTPUT :-


Q9: Create examples to explain promise.all function

ANS :-

                function mypromise(num ){
                    return new Promise((resolve, reject)=>{
                        if(num%2 === 0){
                            resolve("This is even")
                        }
                        else{
                            rej("This is Odd")
                        }
                    })
                }
                
                const mypromise1 = new Promise((resolve, reject)=>{
                    if(true){
                        resolve("hi EAC _01")
                    }
                    else{
                        reject("Soryy !!!!")
                    }
                })
                
                Promise.all([mypromise(20), mypromise1]).then((data)=>{
                    console.log(data)
                }).catch((data)=>{
                    console.log(data)
                })
            

OUTPUT :-