Promises in JS

 Promises in JS


Promises are objects used to handle asynchronous operations in JavaScript. They represent a value that may be available now, in the future, or never.



function fetchData() {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      resolve('Data fetched successfully!');

    }, 2000);

  });

}


fetchData()

  .then(result => {

    console.log(result);

  })

  .catch(error => {

    console.error(error);

  });

In the above example, fetchData returns a promise that resolves after 2 seconds. You can use the .then() method to handle the resolved value and the .catch() method to handle errors.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...