, dequeue
, enqueue
. , , , promises .
class AsyncBlockingQueue {
constructor() {
this.resolvers = [];
this.promises = [];
}
_add() {
this.promises.push(new Promise(resolve => {
this.resolvers.push(resolve);
});
}
enqueue(t) {
if (!this.resolvers.length) this._add();
this.resolvers.shift()(t);
}
dequeue() {
if (!this.promises.length) this._add();
return this.promises.shift();
}
isEmpty() {
return !this.promises.length;
}
isBlocked() {
return !!this.resolvers.length;
}
get length() {
return this.promises.length - this.resolvers.length;
}
}
TypeScript, , -, .
Queue , . . , promises resolvers.