Both promises and async/await are ways of working with asynchronous code in JavaScript.
A promise is an object that represents the result of an asynchronous operation.
It has three possible states: pending, fulfilled, or rejected. Promises provide a convenient way to handle asynchronous results, allowing you to chain together multiple async operations and handle the results in a single place.
Async/await is a more recent addition to JavaScript that makes working with promises even easier.
It allows you to write asynchronous code in a way that looks and behaves like synchronous code. Instead of using then() to handle the results of a promise, you can use the await
keyword to wait for the promise to resolve before moving on to the next line of code.
Here is an example of using promises to make an HTTP request:
function makeRequest() {
return new Promise((resolve, reject) => {
// make the HTTP request
if (requestSuccessful) {
resolve(response);
} else {
reject(error);
}
});
}
makeRequest()
.then(response => {
// handle the successful response
})
.catch(error => {
// handle the error
});
Here is the same example using async/await:
async function makeRequest() {
try {
// make the HTTP request
const response = await fetch('http://example.com');
// handle the successful response
} catch (error) {
// handle the error
}
}
Both promises and async/await make it easier to work with asynchronous code, but async/await provides a cleaner and more concise syntax that makes your code easier to read and understand.