16. Promises, Async/ Await

Que.1 Write one example explaining how you can write a callback function.

  function greeting(name, callback) {
    console.log('Hello ' + name + '!');
    callback();
  }
  
  function sayGoodbye() {
    console.log('Goodbye!');
  }
  
  greeting('Ajay', sayGoodbye);
        

Output:   Hello Ajay!
Goodbye!

Explaination:     So in summary, a callback function is a function that is passed as an argument to another function, and is executed at a later time or in response to some event. In this example, sayGoodbye is a callback function that is executed after the greeting function is called.

Que.2 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
  6
  7

  function printNumbersWithDelay(callback) {
    let count = 1;
    const interval = setInterval(() => {
      console.log(count);
      count++;
      if (count > 7) {
        clearInterval(interval);
        if (callback) {
          callback();
        }
      }
    }, 1000);
  }
  printNumbersWithDelay(() => {
    console.log('All done!');
  });
        

Explaination:     This code defines a function called printNumbersWithDelay that takes a single argument, callback, which is a function that will be executed once the function has finished printing numbers.

Within the function, a variable count is initialized to 1. The function then creates an interval using setInterval, which repeatedly executes a callback function after a specified delay of 1000 milliseconds (1 second). The callback function logs the current value of count to the console and then increments it.

The interval continues to run until count is greater than 7. At that point, the interval is cleared using clearInterval, and if a callback function was provided, it is called.

Finally, the printNumbersWithDelay to the console once the printNumbersWithDelay function has finished executing.

Que.3 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
  6
  7

  function printNumbersWithDelay() {
    return new Promise((resolve, reject) => {
      let i = 1;
      const intervalId = setInterval(() => {
        console.log(i);
        i++;
        if (i > 7) {
          clearInterval(intervalId);
          resolve();
        }
      }, i * 1000);
    });
  }
  
  printNumbersWithDelay()
    .then(() => console.log("Finished!"))
    .catch((error) => console.error(error));
      

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

  function promiseFunction(arg) {
    return new Promise((resolve, reject) => {
      if (arg === "yes") {
        resolve("Promise Resolved");
      } else {
        reject("Promise Rejected");
      }
    });
  }
  promiseFunction("yes")
    .then((result) => console.log(result))
    .catch((error) => console.log(error));
        

Que.5 Create examples to explain callback function

  function fetchData(callback) {
    setTimeout(() => {
      const data = { name: "Ajay", age: 22 };
      callback(data);
    }, 1000);
  }
  
  fetchData((data) => {
    console.log(data); // { name: "Ajay", age: 22 }
  });
        

Explain:     In this example, fetchData simulates an asynchronous operation that takes 1 second to complete. When the operation is done, it calls the callback function with the fetched data. We pass a callback function as an argument to fetchData and log the data to the console when it's returned.

Que.6 Create examples to explain callback hell function

  function getData(callback) {
    setTimeout(function() {
      callback('Data received');
    }, 2000);
  }
  
  getData(function(data) {
    console.log(data);
  
    getData(function(data) {
      console.log(data);
  
      getData(function(data) {
        console.log(data);
      });
    });
  });
        

Que.7 Create examples to explain promises function

  sconst myPromise = new Promise((resolve, reject) => {
  s  setTimeout(() => {
  s    resolve("Hello, World!");
  s  }, 1000);
  s});
  s
  smyPromise.then((message) => {
  s  console.log(message); // logs "Hello, World!" after 1 second
  s});
        

Que.8 Create examples to explain async await function

  
  async function fetchData() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // Fetch data from API
      const data = await response.json(); // Parse response to JSON
      console.log(data); // Log the data
    } catch (error) {
      console.error('Error fetching data:', error); // Log any errors
    }
  }
  
  fetchData(); // Call the async function
        

Que.9 Create examples to explain promise.all function

            
  // Imagine we have three APIs to fetch data from
  const api1 = 'https://jsonplaceholder.typicode.com/todos/1';
  const api2 = 'https://jsonplaceholder.typicode.com/todos/2';
  const api3 = 'https://jsonplaceholder.typicode.com/todos/3';
  
  // We can use `Promise.all` to fetch data from all three APIs simultaneously
  const promises = [fetch(api1), fetch(api2), fetch(api3)];
  
  Promise.all(promises)
    .then(responses => {
      // responses is an array of resolved values from the input promises
      // We can access the data from each response and process it as needed
      const data1 = responses[0].json();
      const data2 = responses[1].json();
      const data3 = responses[2].json();
      console.log(data1, data2, data3);
    })
    .catch(error => {
      // If any of the promises reject, the error will be caught here
      console.error(error);
    });

        
Back
Next
6