-2

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?

Marco Disco
  • 527
  • 7
  • 22
  • 3
    You don't have any promises. And nothing's "autoexecuted", you call the function then put the value it returns in an array. – jonrsharpe Jan 27 '21 at 16:01
  • https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference – Teemu Jan 27 '21 at 16:06

2 Answers2

1

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]();
Blindy
  • 65,249
  • 10
  • 91
  • 131
0

For sequential execution of Promises, you can use reduce on the dynamically create Array of Promise which you have mentioned.