Junior
What is the difference between using Promise and async/await syntax?
sobes.tech AI
Answer from AI
Promise is an object that reflects the eventual completion or failure of an asynchronous operation. It manages asynchronous flows using callbacks .then() and .catch().
async/await is syntactic sugar over Promise, making asynchronous code more readable and similar to synchronous code. A function marked as async always returns a Promise. The await operator can only be used inside an async function and it pauses the execution of the function until the Promise is fulfilled or rejected, then returns its result or throws an exception.
| Aspect | Promise | Async/Await |
|---|---|---|
| Readability | Requires chains of .then() and .catch() |
Looks like synchronous, linear flow |
| Error handling | Uses .catch() |
Uses try...catch blocks |
| Execution flow | Managed by callbacks | Pauses/resumes the function |
| Return value | Promise | Promise (for async functions) or Promise result (for await) |
| Dependency | Standalone mechanism | Built on Promise |
Example with Promise:
// Promise example
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received (Promise)");
}, 1000);
});
}
fetchDataPromise()
.then(data => console.log(data))
.catch(error => console.error(error));
Example with async/await:
// async/await example
function fetchDataAsync() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received (async/await)");
}, 1000);
});
}
async function showData() {
try {
const data = await fetchDataAsync();
console.log(data);
} catch (error) {
console.error(error);
}
}
showData();