paint-brush
How to use Lo-Dash functions with Async/Awaitby@suguru.motegi
26,313 reads
26,313 reads

How to use Lo-Dash functions with Async/Await

by Suguru MotegiAugust 9th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<code class="markup--code markup--p-code">Lo-Dash</code> is a really cool and useful library. If we are able to use the functions with <code class="markup--code markup--p-code">Async/Await</code>, the JavaScript life will be more comfortable.<br>I would like to write the same as <code class="markup--code markup--p-code">Lo-Dash</code> function’s way as much as possible. Because if we already know how to use <code class="markup--code markup--p-code">Lo-Dash</code>, we don’t need to learn new functions. The example code is written as below.
featured image - How to use Lo-Dash functions with Async/Await
Suguru Motegi HackerNoon profile picture


Lo-Dash is a really cool and useful library. If we are able to use the functions with Async/Await, the JavaScript life will be more comfortable.I would like to write the same as Lo-Dash function’s way as much as possible. Because if we already know how to use Lo-Dash, we don’t need to learn new functions. The example code is written as below.



// example 1const array = [1, 2, 3];const result = _.map(array, syncFunc);

// ↓ async/await

const result = await _.map(array, asyncFunc);






function syncFunc(n) {return n * 2;}function asyncFunc(n) {return new Promise(resolve => setTimeout(resolve, 10, n * 2));}

The _.chain makes our code clean, we would also like to use it.






// example 2const array = [1, 2, 3];const result = _.chain(array).map(syncFunc).sum().value();

// ↓ async/await




const result = await _.chain(array).map(asyncFunc).sum().value();

Convert Lo-Dash functions to asynchronous functions

Aigle library which I have developed has the mixin function. It converts Lo-Dash functions to asynchronous functions and assigns them into Aigle. The usage is as below.


const _ = require('lodash');const Aigle = require('aigle');

Aigle.mixin(_);



// example 1const array = [1, 2, 3];const result = await Aigle.map(array, asyncFunc);





// example 2const result = await Aigle.chain(array).map(asyncFunc).sum().value();

// or



const result = await Aigle.resolve(array).map(asyncFunc).sum();

You will be able to use the Lo-Dash functions asynchronously. Furthermore, Aigle already has many functions which have the same functionality as Lo-Dash functions, these functions won’t be converted because they are already optimized.

Conclusion

Aigle will make your code clean the same as Lo-Dash. If you are interested in Aigle, I would love you to read the following articles. Let’s enjoy Async/Await using Aigle.

Reference