针对小程序的异步
因为懒得去配置async 和await的环境了,wx.getStorageSync是同步的就
直接了在这个基础上了一个重入锁的js来实现同步
/***本类主要用来实现同步*/
const lockerKey = "wxlocker";
var lockerContainer={};
/**
* 加锁函数
* 参数:锁名
*
*/
function lock(lockName){
var obj= wx.getStorageSync(lockerKey);
console.log(111);
console.log(obj);
if (typeof obj === "undefined" || obj==null||obj==''){
lockerContainer.lockName = 1;
wx.setStorageSync(lockerKey, lockerContainer);
}else{
lockerContainer = obj;
if (typeof lockerContainer.lockName !== "undefined" && lockerContainer.lockName != null && lockerContainer.lockName != ''){
lockerContainer.lockName = lockerContainer.lockName +1;
}else{
lockerContainer.lockName = 1;
}
//更新锁
wx.setStorageSync(lockerKey, lockerContainer);
}
}
/**
* 解锁函数
* 参数:锁名
*
*/
function unlock(lockName){
var obj = wx.getStorageSync(lockerKey);
console.log(222);
console.log(obj);
if (typeof obj === "undefined" || obj == null || obj == '') {//没有锁过
return;
} else {
lockerContainer = obj;
if (typeof lockerContainer.lockName !== "undefined" && lockerContainer.lockName != null && lockerContainer.lockName != '') {
if (lockerContainer.lockName <=0){
lockerContainer.lockName=0;
return;
}else{
lockerContainer.lockName = lockerContainer.lockName - 1;
}
} else {
return;
}
//更新锁
wx.setStorageSync(lockerKey, lockerContainer);
obj = wx.getStorageSync(lockerKey);
console.log(obj);
}
}
/**
* 是否被锁函数
* 参数:锁名
* 返回值:boolean
*/
function isLockedBy(lockName){
var obj = wx.getStorageSync(lockerKey);
if (typeof obj === "undefined" || obj == null || obj == '') {//没有锁过
return false;
} else {
lockerContainer = obj;
if (typeof lockerContainer.lockName !== "undefined" && lockerContainer.lockName != null && lockerContainer.lockName != '') {
if (lockerContainer.lockName > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
/**
* 等待函数(等待100*millseconds后自动解除)
* 参数:锁名,间隔毫秒,等待解锁完成后的回调函数
*
*/
function wait(lockName, millseconds,callback){
//100次监控后清空锁
var expireTime = 0;
var timer =setInterval(function () {
console.log("wait " + millseconds);
if (!isLockedBy(lockName)){
clearInterval(timer);
callback();
}else{//被锁住了
expireTime++;
if (expireTime > 100) {
lockerContainer.lockName=null;
//清空锁
wx.setStorageSync(lockerKey, lockerContainer);
clearInterval(timer);
}
}
}, millseconds)
}
module.exports = {
wait: wait,
unlock: unlock,
lock: lock
}
用法,加锁多少次就要解锁多少次
lock("mylock")
lock("mylock")
unlock("mylock")
unlock("mylock")
wait("mylock",1000,callback)