Refactor Complex Nested Callbacks into Clean Async/Await Flow
Refactor a nested callback-based event processing function into clean, modular, and maintainable async/await style JavaScript code without changing the behavior or output.
Challenge prompt
You are provided with a function that processes a series of data events using nested callbacks. The current code is hard to read, difficult to maintain, and prone to errors due to callback nesting (callback hell). Refactor this function to use modern JavaScript async/await patterns while preserving its original asynchronous flow and output. Ensure the refactored code is easier to read, modular, and uses error handling effectively. Do not change the logic or the final result the function produces.
Guidance
- • Break down the nested callback logic into smaller, reusable async functions.
- • Use try/catch blocks to handle asynchronous errors gracefully within async functions.
- • Replace callbacks with Promises where needed to leverage async/await syntax.
Hints
- • Consider converting the original callback functions into Promise-returning functions to enable awaiting them.
- • Ensure that you properly await asynchronous operations to maintain execution order.
- • Check that error handling replicates the original behavior by propagating or catching exceptions appropriately.
Starter code
function processEvents(events, onComplete) {
let results = [];
let index = 0;
function processNext() {
if (index >= events.length) {
onComplete(null, results);
return;
}
simulateAsyncEvent(events[index], (err, result) => {
if (err) {
onComplete(err);
return;
}
results.push(result);
index++;
processNext();
});
}
processNext();
}
// Simulates async event processing
function simulateAsyncEvent(event, callback) {
setTimeout(() => {
if (event === 'error') {
callback(new Error('Event processing failed'));
} else {
callback(null, event.toUpperCase());
}
}, 100);
}Expected output
Calling processEvents(['a', 'b', 'c'], callback) should result in callback(null, ['A', 'B', 'C']) Calling processEvents(['a', 'error', 'c'], callback) should result in callback(Error('Event processing failed'))
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.