I have a long array of objects containing:
1) Name of the process (the 'name') 2) A function (the 'task') 3) The arguments for that function (the 'arguments')
Some of the tasks are dependent on other tasks being completed before they can be carried out. I want them to dynamically await the completion of any dependencies.
What I was hoping to do was to have an async function providing the name argument for the functions that are dependent on other parts. In that way a function would be on hold until the task can be executed. I need it to be dynamic, no 2 or 3 lists executed separately. There may be tasks depending on other dependent tasks.
A list of tasks:
let tasks = [
{name: 'numerator', task: insert, arguments: ['part', 'UK', '2010']},
{name: 'divide', task: calculate, arguments: ['UK', '2010', await waitFor('numerator'), await waitFor('denominator')]},
{name: 'denominator', task: insert, arguments: ['whole', 'UK', '2010']}
];
A loop:
tasks.forEach(d => {
d.task(d.arguments);
}
Functions:
async function waitFor(taskName) {
await tasks.find(d => d.name === taskName).task;
return taskName;
}
async function insert(mode, country, year) {
//Connect to database, sum up raw data and insert
}
async function divide(country, year, upper, lower) {
//Connect to database, retrieve the values, divide one by the other and insert
}
Now, I know very well that the above solution does not work. I see two problems: 1) The waitFor function reference the tasks array before it is initialized 2) Promises do not work the way I hoped they would. Execution of the dependent task will not magically be delayed until other tasks are done.
Some may say that this is a stupid way of doing things. I have inherited code where there is a set order and await for every single task and that is very time consuming. I wish to create a system where tasks can be added and everything is automatically coordinated. So the question is:
How should the waitFor function be written and how should it be used in the tasks array for this to work?
Very grateful for help with this.