1import {nanoid} from 'nanoid'; 2 3const locks = new Map<string, string>(); 4 5export interface ILock { 6 key: string; 7 lockId: string; 8 valid: () => boolean; 9 release: () => void; 10} 11 12function requireLock(key: string): ILock { 13 const lockId = nanoid(); 14 locks.set(key, lockId); 15 16 return { 17 key, 18 lockId, 19 /** 锁是否有效 */ 20 valid() { 21 const currentLockId = locks.get(key); 22 return !currentLockId || currentLockId === lockId; 23 }, 24 /** 释放后赋空 */ 25 release() { 26 const currentLockId = locks.get(key); 27 if (currentLockId === lockId) { 28 locks.delete(key); 29 } 30 }, 31 }; 32} 33 34export {requireLock}; 35