Suppose I have the following array:
const routes = [
{ isAsync: true },
{ isAsync: false },
{ isAsync: true },
]
How can I map this to async or sync functions? Something like the following doesn't work:
routes.map(({ isAsync }, index) =>
[isAsync ? 'async' : ''] () => { console.log('isAsync: ', isAsync, index) })
I could something like,
routes.map(({ isAsync }, index) =>
isAsync
? async () => { console.log('isAsync: ', isAsync, index) }
: () => { console.log('isAsync: ', isAsync, index) })
But I'm wondering if it's possible to do it the way I'm trying to in the first example?
Juan Pablo Isaza
I agree with @DBS comment that your second option looks just fine. Nevertheless, for completeness, here is a solution:
const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor
const routes = [{
isAsync: true
},
{
isAsync: false
},
{
isAsync: true
},
];
const funcWithParams = routes.map(({
isAsync
}, index) => new Object({
'func': (isAsync ? Function : AsyncFunction).apply(this, ['isAsync', 'index', `console.log('isAsync: ', isAsync, index)`]),
'isAsync': isAsync,
'index': index
}));
funcWithParams.forEach((funcWithParam) => funcWithParam.func(funcWithParam.isAsync, funcWithParam.index));
Explanation:
For function, Documentation says:
Every JavaScript function is actually a
Function
object
And almost the same for async function:
In JavaScript, every asynchronous function is actually an
AsyncFunction
object.
With a side note:
Note that AsyncFunction is not a global object. It can be obtained with the following code:
Object.getPrototypeOf(async function(){}).constructor
Your requirement for dynamically constructing a function / an async function is possible if you call the constructor of each prototype. for this to be achieved, call it with apply
.
const routes = [{
isAsync: true
},
{
isAsync: false
},
{
isAsync: true
},
];
const result = routes.map(function({
isAsync
}, index) {
return isAsync ? this.async_fn.bind(null, isAsync, index) : this.fn.bind(null, isAsync, index)
}, {
fn: (isAsync, index) => {
console.log('isAsync:', isAsync, index)
},
async_fn: async(isAsync, index) => {
console.log('isAsync:', isAsync, index)
},
});