1

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?

1
  • I think the second option with a named function (to avoid duplication) is probably the best solution, though it will be interesting it anyone does know a way. Commented Oct 4, 2021 at 10:23

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.