js同步锁

2023-11-29  本文已影响0人  一本大书

实现

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
    })
}
上一篇下一篇

猜你喜欢

热点阅读