Skip to content
Advertisement

Javascript Array of Functions get auto executed

I need to make a sequence of Promises that are executed in a queue. They are dynamic so I need to put them in an array (I have found an article that explains how to).

The problem is that my array of functions autoexecuted it self (version with a normal funciton):

const functionTest = () => console.log("ok");

let tasks = [
  functionTest("berlin", "de", "metric"),
  functionTest("london", "en", "metric"),
  functionTest("paris", "fr", "metric"),
  functionTest("new York", "en", "imperial"),
];

I don’t know why, an array of functions is something that I never have done.

Is it normal?

Where is the problem?

Advertisement

Answer

You need to store the call as a lambda function if you want to call it later, like this:

let tasks = [
  () => functionTest("berlin", "de", "metric"),
  () => functionTest("london", "en", "metric"),
  () => functionTest("paris", "fr", "metric"),
  () => functionTest("new York", "en", "imperial"),
];

And you can call them like this:

tasks[0]();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement