Performance: Unhandled rejection handling
This affects the responsiveness and stability of Node.js applications by preventing crashes and unresponsive states caused by unhandled promise rejections.
Jump into concepts and practice - no test required
async function fetchData() { try { const data = await fetch('https://api.example.com/data'); return await data.json(); } catch (error) { console.error('Fetch failed:', error); return null; } } fetchData();
async function fetchData() { const data = await fetch('https://api.example.com/data'); return data.json(); } fetchData(); // No catch or error handling
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No rejection handling | N/A | N/A | N/A | [X] Bad |
| Local try/catch with async/await | N/A | N/A | N/A | [OK] Good |
| Global unhandledRejection logging | N/A | N/A | N/A | [OK] Good |
process.on('unhandledRejection') in a Node.js application?process.on(eventName, callback) to listen to events.process.on('unhandledRejection', handlerFunction).process.on('unhandledRejection', (reason) => {
console.log('Error:', reason.message);
});
Promise.reject(new Error('Failed promise'));new Error('Failed promise'), so reason.message is 'Failed promise'.process.on('unhandledRejection', (error) => {
console.log('Caught:', error);
});
Promise.reject('Oops!');Caught: Oops! instead of an error message. What is the issue?server.close() with a callback to exit after closing. This is correct.