写了个了 redis 加锁的函数,写完发现 promise 嵌套了,感觉有点奇怪。
getLock: function (lockName, seconds) {
var self = this;
lockName = self.REDIS_LOCK_PREFIX + lockName;
var expireTimeInMs = Date.now() + seconds * 1000 + 1;
return self.setnx(lockName, expireTimeInMs).then(function (res) {
if (res === 1) {
return true;
} else {
return self.get(lockName).then(function (previousExpireInMs) {
// 过期死锁
if (previousExpireInMs < Date.now()) {
return self.getset(lockName,expireTimeInMs).then(function (getSetReturnExpireInMs) {
// 重新设置成功
if(previousExpireInMs===getSetReturnExpireInMs){
return true
}else{
return false
}
}).catch(function () {
return false;
})
}else{
return false
}
}).catch(function (err) {
return false;
})
}
}).catch(function (err) {
logger.error(``);
})
},
假设 setnx,get,getset 都是同步函数,那么我想实现的逻辑如下:
function getLock() {
var res = setnx(lockName, expireTimeInMs);
if (res === 1) {
return true;
} else {
var previousExpireInMs = get(lockName);
if (previousExpireInMs < Date.now()) {
var getSetReturnExpireInMs = getset(lockName, expireTimeInMs);
if (previousExpireInMs === getSetReturnExpireInMs) {
return true
} else {
return false
}
} else {
return false
}
}
}
我 promise 的写法感觉姿势不对啊,请同学帮忙指出,谢谢。