DEV Community

ihsaan muhammed
ihsaan muhammed

Posted on

PROMISE in js

A Promise in JavaScript is an object used to handle operations that take some time to complete, especially asynchronous operations.

A** Promise has three states:

Pending – operation is still running
Fulfilled – operation completed successfully
Rejected – operation failed**

Main Uses
Handling asynchronous operations
Promises are commonly used for tasks such as API requests, file operations, and timers.
Fetching data from APIs
The fetch() function returns a Promise.

fetch("https://example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

Enter fullscreen mode Exit fullscreen mode

Avoiding callback hell
Promises make multiple asynchronous operations easier to organize than deeply nested callbacks.
Error handling
The .catch() method can handle errors in asynchronous operations.

myPromise
  .then(result => console.log(result))
  .catch(error => console.log(error));
`
Enter fullscreen mode Exit fullscreen mode

Executing tasks in sequence
Promises can be chained using .then().


login()
  .then(getUser)
  .then(getProfile)
  .then(displayProfile)
  .catch(handleError);
Enter fullscreen mode Exit fullscreen mode

Running multiple asynchronous tasks
Promise.all() can execute multiple Promises and wait for all of them.

Promise.all([task1(), task2(), task3()])
  .then(results => console.log(results));

Enter fullscreen mode Exit fullscreen mode

Using async/await
Promises work together with async and await, making asynchronous code look more like normal sequential code




sync function getData() {
    const response = await fetch("https://example.com/data");
    const data = await response.json();
    console.log(data);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)