• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

29
Views
How to dynamically map an array to async or sync functions?

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?

about 1 month ago ·

Juan Pablo Isaza

2 answers
Answer question

0

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.

about 1 month ago · Juan Pablo Isaza Report

0

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)
  },
});

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.