实现
export default class SpinLock {
isLock = false
synchronized = async (doSomethingSynchronous) => {
while (this.isLock) {
// 如果锁已经被占用,则等待
await new Promise(resolve => {
const timer = setTimeout(() => {
clearTimeout(timer)
resolve()
}, 100)
});
}
this.isLock = true
try {
// 在这里执行需要同步的操作
await doSomethingSynchronous()
} finally {
this.isLock = false
}
}
}
用法:对某个接口请求加锁,保证请求是同步串行
lock = new SpinLock()
request = () => {
this.lock.synchronized(async () => {
const res = await Request.doPostRequest('/xxxx/xxx', {});
this.data = res.data
})
}