Careeroza
Callbacks, Promises and async/await
Callbacks
Example
A function passed to another function and called when the work is done. Nesting many of them leads to "callback hell".
function getUser(id, callback) {
setTimeout(() => callback({ id, name: 'Asha' }), 100);
}
getUser(1, (user) => console.log('Got user:', user.name));Output
Got user: Asha
Promises
Example
A promise is an object for a future value: pending → fulfilled or rejected.
const getUser = (id) =>
new Promise((resolve, reject) => {
setTimeout(() => (id > 0 ? resolve({ id, name: 'Asha' }) : reject(new Error('Invalid id'))), 100);
});
getUser(1)
.then((user) => console.log('then:', user.name))
.catch((err) => console.log('catch:', err.message));
getUser(-1)
.then((user) => console.log('then:', user.name))
.catch((err) => console.log('catch:', err.message));Output
then: Asha catch: Invalid id
async / await
Example
await pauses only the async function until the promise settles; use try/catch for errors.
const wait = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));
async function loadDashboard() {
try {
const user = await wait(100, 'Asha');
const orders = await wait(100, 3);
console.log(user + ' has ' + orders + ' orders');
} catch (e) {
console.log('Failed:', e.message);
}
}
loadDashboard();
console.log('This runs first');Output
This runs first Asha has 3 orders
Run in Parallel
Example
Independent requests should run at the same time with Promise.all.
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
async function main() {
const t = Date.now();
const [user, posts] = await Promise.all([wait(200, 'Asha'), wait(200, ['p1', 'p2'])]);
console.log(user, posts.length, 'posts in about', Math.round((Date.now() - t) / 100) * 100, 'ms');
}
main();Output
Asha 2 posts in about 200 ms