DEV Community

loading...

Discussion on: Callback hell OR try catch hell (tower of terror)

Collapse
ovi profile image
Muhammad Ovi Author

But what if we have all the promise dependend on promise above them, and we want to handle error for each of them?

Collapse
lukeshiru profile image
LUKESHIRU

If every promise depends on the one above them, is even cleaner:

getAreas()
    .then(getTowns)
    .then(getCities)
    .then(getCountries)
    .then(getContinents)
    .then(getPlanets)
    .then(getSolarSystems)
    .then(getGalaxies)
    .catch(handleError);
Enter fullscreen mode Exit fullscreen mode

Or, as I mentioned previously, you can use a reduce:

[
    getAreas,
    getTowns,
    getCities,
    getCountries,
    getContinents,
    getPlanets,
    getSolarSystems,
    getGalaxies
].reduce(
    (previous, promise) => previous.then(promise),
    Promise.resolve()
);
Enter fullscreen mode Exit fullscreen mode

And you can even use an util that returns a tuple with [value, error] in that same reduce if you want to.

Still, the main point in my original comment is:

even if async/await didn't existed, you shouldn't be nesting like that.

What I mean by it is that, before async/await were a thing, nesting promises was seen as a bad practice, so the main argument for async/await shouldn't be "you don't have nesting", but actually "you have better ergonomics in some scenarios", or "is less confusing for people not used to JavaScript's asynchronicity".

Take it this way, you could also compare this two snippets, and in them async/await looks worst than using just promises:

const getAPI = async () => {
    try {
        const response = await fetch(API);
        console.log(await response.response.json());
    } catch (error) {
        console.error(error);
    }
};

// vs

const getAPI = () =>
    fetch(API)
        .then(response => response.json())
        .then(console.log)
        .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Cheers!