Andre Hijaouy
Sep 2, 2018 · 1 min read

The example of callback hell w/ promises used here is not good. That piece of code can be rewritten using promises that doesn’t have the callback hell characteristic of creeping across the screen.

// users to retrieve
const users = [
'W8lbAokuirfdlTJpnsNC5kryuHtu1G53',
'ZinqxnohbXMQdtF6avtlUkxLLknRxCTh',
'ynQePb3RB2JSx4iziGYMM5eXgkwnufS5',
'EtT2haq2sNoWnNjmeyZnfUmZn9Ihfi8w'
];

// array to hold response
let response = [];

// fetch all 4 users and return responses to the response array
function getUsers(userId) {
axios.get(`/users/userId=${users[0]}`).then(res => {
//save the response for user 1
response.push(res);
return axios.get(`/users/userId=${users[1]}`)
}).then(res => {
// save the response for user 2
response.push(res);
return axios.get(`/users/userId=${users[2]}`)
}).then(res => {
// save the response for user 3
response.push(res);
axios.get(`/users/userId=${users[3]}`)
}).then(res => {
// save the response for user 4
response.push(res);
}).catch(err => {
// handle error
console.log(err);
});

}

This is the way that piece of code should be written. Note that it does not move right on the page like callback hell and note there only needs to be one catch block at the end.

There are some valid reasons teams may choose async/await over Promises, but showing misleading of promises to convince a reader to use async/await seems wrong.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade