Before you go, check out these stories!

0
Hackernoon logoHow to use Lo-Dash functions with Async/Await by@suguru.motegi

How to use Lo-Dash functions with Async/Await

Author profile picture

@suguru.motegiSuguru Motegi

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/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 2
const 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 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();
// 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

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.