34 lines
812 B
JavaScript
34 lines
812 B
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();
|
|
},
|
|
}
|
|
} |