Dealing with callback hell with reduce

Dealing with callback hell with reduce

The common way of dealing with the callback hell is by using promises or async/await.

I am interested in this particular case, where we have an api that uses callbacks, an array of async calls to make, and show the end result at the end.

function api(element, callback) { console.log(`start: ${element}`); setTimeout(() => callback(element * 100), element * 100); } const array = [1, 2, 3, 4, 5, 6]; Promise.all( => { return new Promise(resolve => api(element, resolve)); })).then(array => console.log(array)); 

This aproach is not bad, but sometimes the array is too large and it is better to make the calls in sequence instead of all at the same time. Sometimes we just need to do the async calls in order.

This is simple, but we loose the end result.

array.reduce((promise, element) => { return promise.then(() => new Promise(resolve => api(element, resolve))); }, Promise.resolve()).then(() => console.log('done')); 

This solution is still short, but things start to get complicated.

array.reduce((promise, element) => { return promise.then(array => { return new Promise(resolve => { api(element, result => { resolve(array.concat(result)); }); }); }); }, Promise.resolve([])).then(array => console.log(array)); 

I learned that you can compose funcions with reduce and came up with this solution. It is funny how it is simple and only uses pure callbacks.

array.reduce((callback, element) => array => { api(element, result => callback(array.concat(result))); }, array => console.log(array))([]); 

The solution without the end result is also simple.

array.reduce((callback, element) => () => { api(element, callback); }, () => console.log('done'))(); 


Submitted August 13, 2017 at 06:37AM by Lakelava
via reddit


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s