Currently, I have defined two functions as follows:
function getLock() {
let promise, isPending;
if (Math.random() > 0.5) {
promise = new Promise((resolve, reject) => setTimeout(resolve, 1000));
isPending = true;
} else {
promise = Promise.resolve();
isPending = false;
}
return [promise, isPending];
};
function waitForLock() {
const lockAndIsPending = getLock();
const lock = lockAndIsPending[0];
const isPending = lockAndIsPending[1];
if (!isPending) {
return lock;
} else {
return lock.then(waitForLock);
}
}
waitForLock().then(() => console.log("done"));
This is of course for demonstration only. As a necessity of the real world application, getLock
always needs to return a Promise. Also, after the lock has been released once, it has to be checked if it is still released (lock.then(waitForLock)
) because the real release conditions (here modeled by Math.random()
) could have changed meanwhile due to the asynchrony. This introduces recursion.
My current code works fine: waitForLock()
will eventually return because it will happen sometime that getLock
returns isPending=false
, fulfilling the termination condition.
But my goal is to get rid of isPending
as extra return variable. In the future, getLock
should return a promise only. Unfortunately, it is not possible to check whether a given promise is already resolved or not (see here), so I cannot "calculate" isPending
in waitForLock
. So how could I change waitForLock
accordingly?
Edit
The goal is to be able to use any Promise
-returning function for getLock
without special constraints on return or resolve values. So, if possible, the logic should all be in waitForLock
, not in getLock
.