let state = 'A'
async function runTask() {
state = await someApi()
}
// `someApi`'s execution time may vary, as well as its response.
- Initial state is
A, and thenrunTaskget called. - For some reason,
runTaskis called again before the previous call get settled. - Second call to
someApiresolves with responseC, and the state is updated accordingly. - First call to
someApiresolves with responseB, and the state is updated accordingly, which is undesirable.
time state
| A
| A --- runTask
| A someApi(call #1)
| A |
| A |
| A ------------------------ runTask (get called before previous one settles)
| A | someApi(call #2)
| A | ‖
| A | ‖
| A | v
| C --------------------- response #2: C
| C |
| C |
| C v
| B -- response #1: B
| B
| B
v
How should I solve this problem gracefully in javascript? A workaround I can think of is: to assign timestamp on each request and maintain a global lastUpdated variable to prevent any obsolete & late responses from modifying the state. However, it feels dirty and does not scale well since there are usually lots of states and asynchronous actions.
Update
Bounty rewarded on the earliest favorable answer.