How to use Lo-Dash functions with Async/Await
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 1
const array = [1, 2, 3];
const result = _.map(array, syncFunc);// ↓ async/awaitconst 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 2
const array = [1, 2, 3];
const result = _.chain(array)
.map(syncFunc)
.sum()
.value();// ↓ async/awaitconst 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 1
const array = [1, 2, 3];
const result = await Aigle.map(array, asyncFunc);// example 2
const result = await Aigle.chain(array)
.map(asyncFunc)
.sum()
.value();// orconst 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
.