I don't know if this is could be technically called a race condition...
What I have is a big baby, which can only perform one action at the time, but it's being called from an api endpoint; so simultaneous calls can occur
What I think I need to do is somehow make a queue of actions, return a promise to whoever created it, execute the actions synchronously, and resolve the promise with the value returned by the action
Here is the code (it's no real btw, just a snippet representing the problem):
class Baby {
constructor() {
this.current = 'A'
}
go(from, to) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (from === this.current) {
this.current = to
resolve()
} else {
reject(new Error('Unexpected state'))
}
}, 100)
})
}
// In order to perform the action successfully it has to do some steps in some exact order
async doAction() {
await this.go('A', 'B')
await this.go('B', 'C')
await this.go('C', 'A')
console.log('OK')
}
}
module.exports = new Baby()
And is called like this:
const baby = require('./baby')
for (let i = 0; i < 5; i++) {
doAction()
}
Thanks in advance!