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 inprogressPromise
for 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!
CodePudding user response:
To answer your questions, let me first try to explain how your code is working.
Understanding how your code works
Following steps explain the execution of your code:
Script execution start
Call
disallowConcurrency
function, passing in theinitCmp
as an argument.cmpConcurrentFunction
is assigned the return value ofdisallowConcurrency
functionCall
cmpConcurrentFunction
for the first time, passing in'I am called 1 second later'
as an argument. During this invocation,inprogressPromise
is a resolved promise returned byPromise.resolve()
. Awaiting it pauses the function execution.Call
cmpConcurrentFunction
for the second time, passing in'I am called 2 seconds later'
as an argument. During this second invocation,inprogressPromise
is still a resolved promise returned byPromise.resolve()
. Awaiting it pauses the function execution.Synchronous execution of script ends here. Event loop can now start processing the micro-task queue
Function paused as a result of first invocation of
cmpConcurrentFunction
is resumed, callingthen()
method on the promise returned byPromise.resolve()
. The value of theinprogressPromise
is updated by assigning it a new promise returned byinprogressPromise.then(...)
Function paused as a result of second invocation of
cmpConcurrentFunction
is resumed. From step 6, we know thatinprogressPromise
is now a promise returned byinprogressPromise.then(...)
. So, callingthen()
on it, we are simply creating a promise chain, adding a newthen()
method call at the end of the promise chain created in step 6.At this point, we have a chain that looks like this:
inProgressPromise .then(() => fn('I am called 1 second later')) .then(() => fn('I am called 2 seconds later'))
Callback function of the first
then
method is called, which in turn calls thefn
argument, which isinitCmp
function. CallinginitCmp
sets up a timer that resolves the promiseinitCmp
returns after 1 second. When the promise is resolved after 1 second,'I am called 1 second later'
is logged on the console.When the promise returned by the first call to
initComp
function in the callback function of firstthen
method, is resolved, it resolves the promise returned by the firstthen
method. This leads to the invocation of the callback function of the secondthen
method. This again calls theinitComp
function, which then returns a new promise that is resolved after another 1 second.
This explains why you see 'I am called 2 seconds later'
logged on the console after 2 seconds.
Now answering your questions:
But i don't understand why this keeps working if i remove the await inprogressPromise
await inprogressPromise
serves no purpose in your code other than pausing the calls to cmpConcurrentFunction
function. Both calls await the same promise that is returned by Promise.resolve()
.
So the await is not necessary? Why?
Because the output you see on the console is not because of await
, but because of the promise chain (step 7 above) that is constructed as a result of two invocations of the cmpConcurrentFunction
function.
Further more i was expecting this to work :
const disallowConcurrency = (fn) => { let inprogressPromise = Promise.resolve(); return async (...args) => { await inprogressPromise; inprogressPromise = fn(...args); }; };
The above code doesn't works as your original code because now the promise chain isn't constructed which is key to the output your original code produces.
In this code, you simply overwrite the previous value of inprogressPromise
with the promise returned by initComp
function. Calling initComp
function twice sets up two separate timers and they both resolve their respective promises after 1 second each.