Junior
What is the difference between async/await and Promise?
sobes.tech AI
Answer from AI
async/await is syntactic sugar over promises. It allows writing asynchronous code in a more readable, synchronous style, using the async keyword for functions, inside which await is used to wait for the promise to resolve. Promises are objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
| Feature | async/await | Promise |
|---|---|---|
| Syntax | More similar to synchronous code. | Uses .then(), .catch(), .finally() methods. |
| Readability | Often higher, especially in chains. | Can lead to "Callback hell" in complex chains. |
| Error handling | Uses standard try...catch. |
Uses .catch() or the second argument in .then(). |
| Parallelism | Requires explicit use of Promise.all() or Promise.allSettled(). |
Can be more explicit but less readable without async/await. |
// Promise example
function getDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
}
getDataPromise()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
// async/await example
async function getDataAsync() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data received');
}, 1000);
});
}
async function processData() {
try {
const data = await getDataAsync();
console.log(data);
} catch (error) {
console.error(error);
}
}
processData();