Understanding JavaScript Promises: Simplifying Asynchronous Code

Understanding JavaScript Promises: Simplifying Asynchronous Code

ยท

1 min read

JavaScript promises are a powerful way to handle asynchronous operations, making your code cleaner and more manageable. Let's dive into how promises work and how to use them effectively.

Creating a Promise

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

myPromise.then((result) => {
  console.log(result); // 'Success!'
}).catch((error) => {
  console.error(error);
});
Using async/await

The async/await syntax provides a more readable way to work with promises, making your asynchronous code look synchronous.

Example:

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
};

fetchData();
ย