A
promise is an
asynchronous action that may be completed at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user.
Promises provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks.
The Promise object takes a callback function as a parameter, which, in turn, takes
two parameters, resolve and reject. The promise is either fulfilled or
rejected.
Here's an in-depth look at what Promises are and how they work:
Basics of Promise
A promise created using the promise constructor in JavaScript.
let promise = new Promise((resolve, reject) => {
// Asynchronous operation here
if (/* operation is successful */) {
resolve(result); // Successfully completed
} else {
reject(error); // Failed
}
});
States
A Promise has three states:
Pending: The initial state. The operation is ongoing.
Fulfilled: The operation was completed successfully.
Rejected: The operation failed.
Working with Promises
Chaining with .then()
Once a Promise is fulfilled or rejected, you can handle the result or error using
.then() and .catch():
promise.then((result) => {
// Handle the result
}).catch((error) => {
// Handle the error
});
You can add multiple .then() methods to handle a sequence of asynchronous operations:
promise
.then((result1) => {
// Handle the result of the first operation
return anotherAsyncOperation(result1);
})
.then((result2) => {
// Handle the result of the second operation
})
.catch((error) => {
// Handle any error that occurs in the chain
});
Using .finally()
The .finally() method is used to execute a callback once the Promise is settled
(fulfilled or rejected):
promise
.then((result) => {
// Handle the result
})
.catch((error) => {
// Handle the error
})
.finally(() => {
// Cleanup or final actions
});
Summary
Promises represent the eventual completion or failure of asynchronous operations.
They have three states: pending, fulfilled, and
rejected.
Use .then() for handling fulfilled results, .catch() for handling errors, and
.finally() for cleanup actions.
Promise.all() and Promise.race() help in combining multiple Promises.
async and await provide a more synchronous-like way to handle asynchronous code.
Example: Fetch Data from an API using Promises
// Function to fetch data from an API
function fetchData() {
// Use the fetch API to get data from the given URL
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
// Check if the response status is OK (status code 200)
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the JSON from the response
return response.json();
})
.then(data => {
// Handle the data
console.log('Data:', data);
})
.catch(error => {
// Handle any errors that occur
console.error('There was a problem with the fetch operation:', error);
});
}
// Call the function to fetch data
fetchData();
Explanation:
fetch('https://jsonplaceholder.typicode.com/posts/1'): Initiates a network request to the specified URL.
fetch returns a Promise that resolves to the Response object representing the response to the request.
.then(response => {...}): The first
.then() method processes the Response object. The
response.ok property checks if the response status is in the range 200-299, indicating a successful request.
return response.json();: If the response is okay, we call
response.json() to parse the JSON body text from the response. This returns a Promise that resolves to the parsed JSON data.
.then(data => {...}): The second
.then() method processes the parsed JSON data. Here, we can handle the data, such as logging it to the console.
.catch(error => {...}): The
.catch() method handles any errors that occur during the fetch operation or while processing the response. This includes network errors and the errors thrown if the response is not ok.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A promise is an asynchronous action that may be completed at some point in the future and produce a value. This value is not necessarily known at the time of its creation. Once the value is produced, it notifies the user.
Promises provide a robust way to wrap the result of asynchronous work, overcoming the problem of deeply nested callbacks.
The Promise object takes a callback function as a parameter, which, in turn, takes two parameters, resolve and reject. The promise is either fulfilled or rejected.
Here's an in-depth look at what Promises are and how they work:
Basics of Promise
A promise created using the
promiseconstructor in JavaScript.States
A Promise has three states:
Working with Promises
Chaining with
.then()Once a Promise is fulfilled or rejected, you can handle the result or error using
.then()and.catch():You can add multiple
.then()methods to handle a sequence of asynchronous operations:Using
.finally()The
.finally()method is used to execute a callback once the Promise is settled (fulfilled or rejected):Summary
.then()for handling fulfilled results,.catch()for handling errors, and.finally()for cleanup actions.Promise.all()andPromise.race()help in combining multiple Promises.asyncandawaitprovide a more synchronous-like way to handle asynchronous code.Example: Fetch Data from an API using Promises
Explanation:
fetch('https://jsonplaceholder.typicode.com/posts/1'): Initiates a network request to the specified URL.fetchreturns a Promise that resolves to theResponseobject representing the response to the request..then(response => {...}): The first.then()method processes theResponseobject. Theresponse.okproperty checks if the response status is in the range 200-299, indicating a successful request.return response.json();: If the response is okay, we callresponse.json()to parse the JSON body text from the response. This returns a Promise that resolves to the parsed JSON data..then(data => {...}): The second.then()method processes the parsed JSON data. Here, we can handle the data, such as logging it to the console..catch(error => {...}): The.catch()method handles any errors that occur during the fetch operation or while processing the response. This includes network errors and the errors thrown if the response is not ok.Read also,
Implementation of Data Structures in JavaScript
Explain the concept and use DOM Manipulation