44 lines
1.1 KiB
JavaScript
44 lines
1.1 KiB
JavaScript
/* Simple asynchronous queue.
|
|
To make `get` blocking, we create a new promise and store its `resolve` function in `resolvers`.
|
|
The next time an item is added to the queue, it will be resolved.
|
|
*/
|
|
|
|
export default function() {
|
|
return {
|
|
items: [],
|
|
|
|
resolvers: [],
|
|
|
|
size() {
|
|
return this.items.length;
|
|
},
|
|
|
|
put(item) {
|
|
this.items.push(item);
|
|
let resolver = this.resolvers.shift();
|
|
if (resolver) {
|
|
resolver();
|
|
}
|
|
},
|
|
|
|
async get() {
|
|
if (this.items.length === 0) {
|
|
await new Promise((resolve, reject) => {
|
|
this.resolvers.push(resolve);
|
|
})
|
|
}
|
|
|
|
return this.items.shift();
|
|
},
|
|
|
|
find_remove(pred) {
|
|
for (let i=0; i<this.items.length; i++) {
|
|
if (pred(this.items[i])) {
|
|
this.items.splice(i, 1);
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
},
|
|
}
|
|
} |