修复lockUtils在wx上报错问题

This commit is contained in:
yhh
2020-08-06 12:01:20 +08:00
parent d0199e357b
commit ab3f38c6a8
10 changed files with 47 additions and 40 deletions

View File

@@ -1,7 +1,4 @@
const THREAD_ID = `${Math.floor(Math.random() * 1000)}-${Date.now()}`;
const setItem = egret.localStorage.setItem.bind(localStorage);
const getItem = egret.localStorage.getItem.bind(localStorage);
const removeItem = egret.localStorage.removeItem.bind(localStorage);
const nextTick = fn => {
setTimeout(fn, 0);
@@ -13,36 +10,42 @@ const nextTick = fn => {
class LockUtils {
private _keyX: string;
private _keyY: string;
private setItem;
private getItem;
private removeItem;
constructor(key) {
this._keyX = `mutex_key_${key}_X`;
this._keyY = `mutex_key_${key}_Y`;
this.setItem = egret.localStorage.setItem.bind(localStorage);
this.getItem = egret.localStorage.getItem.bind(localStorage);
this.removeItem = egret.localStorage.removeItem.bind(localStorage);
}
public lock() {
return new Promise((resolve, reject) => {
const fn = () => {
setItem(this._keyX, THREAD_ID);
if (!getItem(this._keyY) === null) {
this.setItem(this._keyX, THREAD_ID);
if (!this.getItem(this._keyY) === null) {
// restart
nextTick(fn);
}
setItem(this._keyY, THREAD_ID);
if (getItem(this._keyX) !== THREAD_ID) {
this.setItem(this._keyY, THREAD_ID);
if (this.getItem(this._keyX) !== THREAD_ID) {
// delay
setTimeout(() => {
if (getItem(this._keyY) !== THREAD_ID) {
if (this.getItem(this._keyY) !== THREAD_ID) {
// restart
nextTick(fn);
return;
}
// critical section
resolve();
removeItem(this._keyY);
this.removeItem(this._keyY);
}, 10);
} else {
resolve();
removeItem(this._keyY);
this.removeItem(this._keyY);
}
};