How do you escape callback hell?
The way out is to change the callback-based functions into functions that return promises. After that you can write the sequence as a flat chain, or as an async function that waits for one step before it starts the next one. The nesting disappears because every step now hands you a value that you can pass to the step after it.
// The promise version of a two step sequence.
function readFileAsync(name) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve('content of ' + name);
}, 5);
});
}
function parseAsync(text) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve({ lines: text.length });
}, 5);
});
}
async function run() {
const text = await readFileAsync('notes.txt');
const parsed = await parseAsync(text);
console.log('lines:', parsed.lines);
}
run();The change itself is small and mechanical. A callback function becomes a function that returns a promise, and the place that calls it changes from passing a callback to using await. The steps keep exactly the same order, but now they sit next to each other instead of sitting inside each other.
Two techniques are worth naming here. The first one is a generic promisify helper, which turns any function that follows the error-first callback style into a function that returns a promise. You write it once, and then every old API in your project becomes chainable. The second one is to wrap a whole callback-based module at its edge, so that the rest of your code only ever sees promises.
There is a middle option as well. Some teams keep the callback API but give every step a name and pass the next step in by hand. That is called continuation passing style. It flattens the structure without changing the contract of the API, and it is a reasonable choice when you cannot change the API that you are calling.