DEV Community

Discussion on: JavaScript: Promises and Why Async/Await Wins the Battle

Collapse
 
leadiv profile image
Paul Borrego

Hi Nick thanks for writing on this subject. I have yet to use async/await in a project but could see how it can be useful.

One thing I wanted to note from your section "Callback Hell?" is that the promises in that section could be structured to avoid that callback hell.

I realize that the example is to show a good contrast between callback hell and async/await but it seemed to be presented as promises are not able to be a solution for callback hell. I thought of two ways the promises could be restructured:

const getUser = (user) => () => {

    return axios
        .get(`/users/userId=${user}`)
        .then((res) => response.push(res));
}

function getUsers(users) {

    const [
        getFirstUser,
        getSecondUser,
        getThirdUser,
        getFourthUser
    ] = users.map(getUser);

    getFirstUser()
        .then(getSecondUser)
        .then(getThirdUser)
        .then(getFourthUser)
        .catch(console.log);
}

This is a generic version of the previous one...

const getUser = (user) => () => { 

    return axios
        .get(`/users/userId=${user}`)
        .then((res) => response.push(res));
}

const promiseChain = (all, next) => all.then(next);

function getUsers(users) {

    users
        .map(getUser)
        .reduce(promiseChain, Promise.resolve())
        .catch(console.log);
}

Still not a clear as the async/await version but does the same thing and does avoid the callback hell.