Sharing Top Content from the Angular-sphere.

Asynchronous Reduce in JavaScript: #javascript #node #nodejs #angular #angularjs #react

Asynchronous Reduce in JavaScript:  #javascript #node #nodejs #angular #angularjs #react

  • Let’s start with a naïve implementation, using just normal iteration: – – This small code inside is, basically, a reducer, but with asynchronous flow!
  • Let’s generalize it, so we’ll pass handler there: – – Now we have fully generalized reducer, but as you can see, the amount of code in our function stayed almost the same in size – so, in case you use once or twice, it might be not that beneficial to…
  • Well, another new feature of modern JS is generators, and you can use them to essentially repeat the same behaviour (and almost the syntax!)
  • The only problem is the following: – – Apparently, not so many projects/people dive into generators, due to their complicated nature and alternatives, and because of that, I’ll separate our immediately, so you can hide implementation details: – – You can see that our interface remained the same, but the…
  • While the amount of code is not bigger (it might be even smaller), it is less readable and has to wrap your head around it – however, it works exactly the same.

The blog of Seva Zaikov

Reduce is a very powerful concept, coming from the functional programming (also known as

fold

), which allows to build any other iteration function –

sum

product

map

filter

and so on. However, how can we achieve asynchronous reduce, so requests are executed consecutively, so we can, for example, use previous results in the future calls?

In our example, I won’t use previous result, but rely on the fact that we need to execute these requests in this specific order

Let’s start with a naïve implementation, using just normal iteration:

async function createLinks ( links ) { const results = []; for ( link of links ) { const res = await createLink ( link ); results . push ( res ); } return results ; } const links = [ url1 , url2 , url3 , url4 , url5 ]; createLinks ( links );

This small code inside is, basically, a reducer, but with asynchronous flow! Let’s generalize it, so we’ll pass handler there:

async function asyncReduce ( array , handler , startingValue ) { let result = startingValue ; for ( value of array ) { // `await` will transform result of the function to the promise, // even it is a synchronous call result = await handler ( result , value ); } return result ; } function createLinks (…

Seva Zaikov

Comments are closed, but trackbacks and pingbacks are open.