I have a class with multiple methods, each method either call async functions, or manipulating data created by other methods.
How can I make sure that calling class methods would wait for previous method finish before proceeding?
Here is a simple example that calls random methods of the class, each method takes random number of seconds to execute, I need to make sure that each called method waited for result of previous method:
class Test
{
constructor()
{
//ignore the constructor, it's simplified for this example and does not play any role in the question
const list = [...Array(~~(Math.random()*3)+3)].map(e=>~~(Math.random()*3+1));
console.log("expected: " + list);
list.forEach(f => this["method_" + f]());
}
method_1()
{
return new Promise(resolve => setTimeout(() =>
{
console.log(1);
resolve("res 1");
}, Math.random() * 1000 + 100));
}
method_2()
{
return new Promise(resolve => setTimeout(() =>
{
console.log(2);
resolve("res 2");
}, Math.random() * 1000 + 100));
}
method_3()
{
func3();
}
}
new Test();
function func3()
{
new Promise(resolve => setTimeout(() =>
{
console.log(3);
resolve("res 3");
}, Math.random() * 1000 + 100));
}
I can't use then
method, because each method doesn't know which method was executed before it...or can I?
I was thinking about adding a sort of queue, where called method would be placed when called, and executed when previous promise was resolved...not sure if that would be a best approach.