What Is Callback Hell & How To Solve Callback Hell
asyncFunction1(arg1, function(err, result1) {
if (err) {
handleError(err);
} else {
asyncFunction2(result1, function(err, result2) {
if (err) {
handleError(err);
} else {
asyncFunction3(result2, function(err, result3) {
if (err) {
handleError(err);
} else {
// More nested callbacks...
}
});
}
});
}
});
To solve callback hell and make code more readable and maintainable, several approaches can be used:
领英推荐
asyncFunction1(arg1)
.then(result1 => asyncFunction2(result1))
.then(result2 => asyncFunction3(result2))
.then(result3 => {
// Continue with the result3
})
.catch(err => handleError(err));
try {
const result1 = await asyncFunction1(arg1);
const result2 = await asyncFunction2(result1);
const result3 = await asyncFunction3(result2);
// Continue with the result3
} catch (err) {
handleError(err);
}