JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
What are the pros and cons of promises over callbacks
Below are the list of pros and cons of promises over callbacks,
Pros:
- It avoids callback hell which is unreadable
- Easy to write sequential asynchronous code with .then()
- Easy to write parallel asynchronous code with Promise.all()
- Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)
Cons:
- It makes little complex code
- You need to load a polyfill if ES6 is not supported
Practical Code Example
javascript
// Callback Hell vs Promise Chain:
// Callback: Inversion of control, no centralized error bubbling
fetchUser(id, (err, user) => {
if (err) return handleErr(err);
fetchPermissions(user, (err, perms) => {
if (err) return handleErr(err);
// ...
});
});
// Promise: Guaranteed resolution, centralized .catch(), clean async/await
async function load() {
try {
const user = await fetchUser(id);
const perms = await fetchPermissions(user);
} catch (err) {
handleErr(err);
}
}