React Hook implementing a queue with optional concurrency limit.
A React Hook implementing a queue for sync or async tasks, with optional concurrency limit.
Inspired by @caolan/async.queue.
Infinity
or less than 1 for no concurrency limit.id
(some unique value thattask
(aimport useAsyncQueue from 'use-async-queue';
// Example shows a task fetching a url, but a task can be any operation.
const url = 'some url';
const inflight = task => {
console.log(`starting ${task.id}`);
console.dir(stats); // { numPending: 0, numInFlight: 1, numDone: 0}
};
const done = async task => {
const result = await task.result;
console.log(`finished ${task.id}: ${result}`);
console.dir(stats); // { numPending: 0, numInFlight: 0, numDone: 1}
};
const drain = () => {
console.log('all done');
console.dir(stats); // { numPending: 0, numInFlight: 0, numDone: 1}
};
const { add, stats } = useAsyncQueue({
concurrency: 1,
inflight,
done,
drain,
});
add({
id: url,
task: () => {
return fetch(url).then(res => res.text());
},
});
console.dir(stats); // { numPending: 1, numInFlight: 0, numDone: 0}