There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'.
All these operations occur at runtime, with limited control over their order. Here is a simplified representation:
type State = {
state: number
}
let localState: State = {
state: 1000
}
const promiseTimeout = (time: number, value: number) => () => new Promise(
(resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
);
const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
.then(res => {
localState.state = res
console.log(localState)
})
post(1000, localState); // initial value of localState is 1000
post(3000, localState); // initial value of localState is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000
This model clearly has an issue, as both calls to post
are reading the same value of localState
when they should be executed sequentially.
If all calls were determined at compile time, the solution would involve chaining promises like this:
post(1000, localState)
.then(() => post(3000, localState)) // localState at call time becomes 2000
What would be the approach to fix this situation?