Skip to content

How to set up a function dynamically without calling it in javascript?

I have a function which calls multiple functions at the same time and waits until all of them are finished. It’s working as intended. It’s labeled as parallel below

I’ve got an array which I want to map into a function with the param for each value in the array. However as you might imagine, the function is being called right when it’s being mapped so the results are not being returned to the parallel results. Below is an example of what I’m trying to do.

Any ideas on how I can do this & return the results to the parallel function?

Currently doing

let array = [1,2,3,4,5];
r = await parallel(
    doStuff(array[0]),
    doStuff(array[1]),
    doStuff(array[2]),
    doStuff(array[3]),
    doStuff(array[4]),
  );
  if(r.err.code) return r;

Would like to do

let array = [1,2,3,4,5];

r = await parallel(array.map(v => doStuff(v)))
if(r.err.code) return r;

Parallel

async function waitForAll(...functions) {
  return await Promise.all(functions)
}

const parallel = async (...functions) => {
  const d = {err: {code:0,message:""},res:{}}; let r,sql,vars;

  r = await waitForAll(...functions)
  for(let i in r){ if(r[i].err.code) return r[i]; }

  d.res = r;

  return d;
}

module.exports = {
  parallel
}

Edit: doStuff() is async

Answer

Since parallel accepts any number of separate arguments, it looks like all you need to do is spread the result of mapping into the call. Right now you’re only passing a single array as the first argument.

const array = [1,2,3,4,5];
const r = await parallel(...array.map(v => doStuff(v)))
if(r.err.code) return r;

Or change parallel‘s implementation to accept an array as a single argument

const parallel = async (functions) => {

and do

const r = await parallel(array.map(v => doStuff(v)))

Unless doStuff has different behavior depending on whether its second or more arguments are defined, you might be able to simplify to

const r = await parallel(array.map(doStuff))

removing the inline call.