It's useful for the situation like "queue some processing like building up to 1, and do not run at the same time".
I didn't came up with good name.
import Queue from "promise-queue";
const pBlah1 = (promiseGetter) => {
const maxConcurrent = 1;
const maxQueue = 1;
const queue = new Queue(maxConcurrent, maxQueue);
return () => queue.add(promiseGetter).catch((e) => {if (e.message !== 'Queue limit reached') throw e;})
}
NOTE: this is fully written by me and publishing under public domain.
const pBlah2 = (promiseGetter) => {
let waitProm = null;
let waitResolve = null;
let waitReject = null;
let running = false;
const done = () => {
const waitResolveOld = waitResolve;
const waitRejectOld = waitReject;
running = false;
waitProm = null;
waitResolve = null;
waitReject = null;
if (waitResolveOld) {
promiseGetter()
.then((v) => {
done();
waitResolveOld(v);
})
.catch((e) => {
done();
waitRejectOld(e);
});
}
};
return () => {
if (running) {
if (!waitProm) {
waitProm = new Promise((resolve, reject) => {
waitResolve = resolve;
waitReject = reject;
});
}
return waitProm;
}
running = true;
return promiseGetter()
.then((v) => {
done();
return v;
})
.catch((e) => {
done();
throw e;
});
};
};
const wait = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
const a = async () => {
await wait(2000);
console.log("hi");
};
const f = pBlah1(a);
// const f = pBlah2(a);
(async () => {
f(); // start immediately
await wait(500);
f(); // queued because running
await wait(500);
f(); // ignored because running and queue is full
})();
hi
is only shown 2 times.
p-limit
: this will run all queued promises.p-debounce
: this will run concurrentlyp-queue
: no option to limit max lengthpromise-queue
: easy for the specific casePay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too