In this coding challenge, you will have the opportunity to improve the readability and maintainability of a deeply nested asynchronous code structure that uses callback functions. The goal is to refactor the given code, which exhibits the infamous "Callback Hell" pattern, into a cleaner and more organized structure using Promises.
function asynchronousRequest(args, callback) {
// Throw an error if no arguments are passed
if (!args) {
return callback(new Error('Whoa! Something went wrong.'))
} else {
return setTimeout(
// Just adding in a random number so it seems like the contrived asynchronous function
// returned different data
() => callback(null, { body: args + ' ' + Math.floor(Math.random() * 10) }),
500,
)
}
}
// Nested asynchronous requests
function callbackHell() {
asynchronousRequest('First', function first(error, response) {
if (error) {
console.log(error)
return
}
console.log(response.body)
asynchronousRequest('Second', function second(error, response) {
if (error) {
console.log(error)
return
}
console.log(response.body)
asynchronousRequest(null, function third(error, response) {
if (error) {
console.log(error)
return
}
console.log(response.body)
})
})
})
}
// Execute
callbackHell()
- Refactor the
asynchronousRequest
function to return a Promise instead of using callbacks. - Rewrite the
callbackHell
function using Promises to eliminate the callback pyramid and achieve a more structured and readable code. - Ensure that the refactored code produces the same results as the original code.
- Fork this repository
- Clone forked repository
- Create a new branch
git checkout -b solution
- Create a folder of your nickname
mkdir nickname
- Create files
sol.js
in your folder - Commit and push your changes
- Create a Pull Request to original repository