Performance: Promises for cleaner async
This concept affects how asynchronous operations impact the event loop and responsiveness of the application.
Jump into concepts and practice - no test required
function fetchData() {
return new Promise((resolve, reject) => {
asyncHttpRequest('https://api.example.com/data', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
fetchData().then(result => console.log(result));function fetchData() {
const data = syncHttpRequest('https://api.example.com/data');
return data;
}
const result = fetchData();
console.log(result);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking call | N/A | Blocks event loop | Blocks rendering | [X] Bad |
| Async with Promises | N/A | Non-blocking | No blocking, smooth rendering | [OK] Good |
const promise = new Promise((resolve) => {
setTimeout(() => resolve('Done'), 100);
});
promise.then(result => console.log(result));
console.log('Start');const p = new Promise((resolve, reject) => {
resolve('Success');
reject('Error');
});
p.then(result => console.log(result))
.catch(error => console.log(error));