RT @JavaScriptDaily: Asynchronous Reduce in JavaScript: #javascript #node #nodejs #angular…

  • 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

@Javascript_Devz: RT @JavaScriptDaily: Asynchronous Reduce in JavaScript: #javascript #node #nodejs #angular…

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

JSFeeds责编内容来自:JSFeeds (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » RT @JavaScriptDaily: Asynchronous Reduce in JavaScript: #javascript #node #nodejs #angular…

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录