Skip to content

Promises & Async/Await

A Promise is an object representing the eventual result (or failure) of an asynchronous operation.

  • Pending - Waiting for result
  • Fulfilled - Succeeded with a value
  • Rejected - Failed with an error
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ id: 1, name: 'Notex' });
}, 1000);
});
};
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts(),
]);
PatternProsCons
CallbacksSimpleCallback hell
PromisesChainableVerbose
Async/AwaitReadableNeeds try/catch