2022-01-25 12:29:53 +08:00

41 lines
882 B
JavaScript

const utils = require('./utils');
class Cond {
constructor() {
this.waitList = [];
}
async wait(timeout) {
return new Promise((resolve) => {
const waiterIdx = this.waitList.length;
this.waitList.push({
'resolve': resolve,
'timer': setTimeout(() => {
if (waiterIdx < this.waitList.length &&
this.waitList[waiterIdx]['resolve'] == resolve) {
this.waitList = this.waitList.splice(waiterIdx, 1);
} else {
utils.throwError('cond waiterIdx error');
}
resolve();
}, timeout)
});
});
}
notifyAll() {
if (this.waitList.length > 0) {
const waitListCopy = this.waitList;
this.waitList = [];
waitListCopy.forEach((v) => {
clearTimeout(v['timer']);
v['resolve']();
});
}
}
};
exports.Cond = Cond;