i'm trying to avoid concurrency of a async function in order to wait for the first call of this function to be finished before i can call it again the same function :
const disallowConcurrency = (fn) => {
let inprogressPromise = Promise.resolve();
return async(...args) => {
await inprogressPromise;
inprogressPromise = inprogressPromise.then(() => fn(...args));
};
};
const initCmp = async(arg) => {
return new Promise((res) => {
console.log('executed');
setTimeout(() => res(console.log(arg)), 1000);
});
};
const cmpConcurrentFunction = disallowConcurrency(initCmp);
cmpConcurrentFunction('I am called 1 second later');
cmpConcurrentFunction('I am called 2 seconds later');
So here i'm creating a closure with a promise as a value passed to the inner function.
The return function will wait for the previous call ( in the first run it's a resolved Promise ) and the will assign to inprogressPromise the promise returned by the then which in this case will be a new Promise returned by the initCmp function. So next time we call the function it will wait for the previous one to be done. At least this is how i'm understanding it. Did i get it right?
But i don't understand why this keeps working if i remove the await inprogressPromisefor example like this :
const disallowConcurrency = (fn) => {
let inprogressPromise = Promise.resolve();
return async (...args) => {
inprogressPromise = inprogressPromise.then(() => fn(...args));
};
};
So the await is not necessary? Why?
Further more i was expecting this to work :
const disallowConcurrency = (fn) => {
let inprogressPromise = Promise.resolve();
return async (...args) => {
await inprogressPromise;
inprogressPromise = fn(...args);
};
};
Because i was thinking that first i'm awaiting for the previous promise to be done and then i would call and assign the returned promise on the inprogressPromise.
But it's not working and the two functions are called at the same time.
Can someone clarify me what's going on here?
If you try the code you will see that the second call
cmpConcurrentFunction("I am called 2 seconds later")
will wait for the first promise to be done.
Basically i have written a node package that gets imported into the browser in a web app through npm. This node package library has an init function that has some async code and can be called multiple time in different part of the code. If is called a second time for example i want to be sure that the first execution will be done before trying to execute the code again.
But my point is trying to understand why that code works and why it doesn't if i use the last version
Thanks!