[英]How to avoid this “race condition”?
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; 我有一个大婴儿,一次只能执行一个动作,但是它是从api端点调用的; 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! 提前致谢!
Thanks to Bergi 's tips, this is the final solution: 感谢Bergi的技巧,这是最终的解决方案:
Basically, this keeps a chain of promises and when a new action needs to be added it's chained to the current chain of promises 基本上,这保持了承诺链,当需要添加新操作时,它将被链接到当前的承诺链
const baby = {
current: 'A',
action: Promise.resolve(),
go(from, to) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (from === this.current) {
this.current = to
resolve()
} else {
reject(new Error('Unexpected state'))
}
}, 100)
})
},
doAction() {
this.action = this.action.then(async () => {
await this.go('A', 'B')
await this.go('B', 'C')
await this.go('C', 'A')
console.log('OK')
})
}
}
baby.doAction()
baby.doAction()
baby.doAction()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.