Add pqueue helper (untested)

This commit is contained in:
Talia 2022-03-31 15:36:48 +02:00
parent cdaeac1a9f
commit 8ea23e620d

35
pqueue.js Normal file
View file

@ -0,0 +1,35 @@
const queryable = promise => {
let result = promise.then(result => {
q.result = result
q.done = true
}).catch(error => {
q.error = error
q.done = true
})
return result
}
export default () => {
const queue = []
const delayed = new Map()
loop = () => {
for (promise of queue.splice(0, queue.findIndex(promise => !promise.done))) {
if (promise.result) {
delayed.get(promise).resolve(promise.result)
} else if (promise.error) {
delayed.get(promise).reject(promise.error)
} else {
break
}
}
}
return promise => {
promise = queryable(promise)
queue.push(promise)
promise.finally(loop)
const result = new Promise(fulfill, reject => delayed.set(promise, {fulfill, reject}))
return result
}
}