0

There is an array of functions that execute different code. It is necessary to make one function out of these functions, when called, all functions from the array would be executed at once.

const a = ()=>{console.log("1")};
const b = ()=>{console.log("2")};
const arr = [a,b];
const fn = () =>{
 arr[0]();
 arr[1]();
}

I need to make such a result in code, rather than manually calling functions.

I tried to do this by simply iterating through the array using a for loop, but the question is, is there any way to do this without increasing the index? Should I use it as a recursive function or something else?

Solving the problem using a loop:

const fn = () =>{
 for(let i = 0; i < arr.length; i++){
  arr[i]();
 }
}

Is there some solution that doesn't use a loop? Maybe nest a function within a function somehow?

2
  • 4
    How about arr.forEach(f => f())? Commented Apr 4, 2024 at 18:17
  • Why are you wanting to avoid increasing the index? It's just a variable? Commented Apr 4, 2024 at 18:17

2 Answers 2

0

Here's one I use, to run them asynchronously in a way. This is to avoid hanging the event loop, there is a small timeout between the calls.

function run_all(queue) {
  if (!queue.length) {
    return;
  }

  function do_one(foo, foo_then) {
    foo();
    setTimeout(foo_then)
  }

  var first = queue.shift();
  do_one(first, function() {
    run_all(queue)
  })
}

var arr = []
arr.push(() => console.log("hello"))
arr.push(() => console.log("hello 2"))
run_all(arr)

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

Comments

0

You can use the forEach() method like this:

const a =()=>{console.log("1")};
const b =()=>{console.log("2")};
const c =()=>{console.log("2")};
const d =()=>{console.log("2")};
const e =()=>{console.log("2")};
const f =()=>{console.log("2")};
const arr = [a,b,c,d,e,f];

arr.forEach(x => x());

/* Or wrap it in another function if you want to run it whenever needed

const func = () => arr.forEach(x => x());
func();

*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.