UNPKG

use-async-queue

Version:
3 lines (2 loc) 1.1 kB
import{useState as n,useRef as t,useEffect as r,useCallback as e}from"react";import u from"next-tick";function i(i){const{done:c,drain:m,inflight:o}=i;let{concurrency:s}=i;s=s||Infinity,s<1&&(s=Infinity);const[g,h]=n({numPending:0,numInFlight:0,numDone:0}),d=t(!0),l=t([]),f=t([]);r(()=>{if(g.numDone>0&&m&&0===l.current.length&&0===f.current.length&&!d.current)return d.current=!0,u(m);for(;l.current.length<s&&f.current.length>0;){d.current=!1;const n=f.current.shift();if(n){l.current.push(n),h(n=>({...n,numPending:n.numPending-1,numInFlight:n.numInFlight+1})),o&&o({...n,stats:g});const t=n.task();t.then(()=>{l.current.pop(),h(n=>({...n,numInFlight:n.numInFlight-1,numDone:n.numDone+1})),c&&c({...n,result:t,stats:g})}).catch(()=>{l.current.pop(),h(n=>({...n,numInFlight:n.numInFlight-1,numDone:n.numDone+1})),c&&c({...n,result:t,stats:g})})}}},[s,c,m,o,g]);const a=e(n=>{f.current.find(t=>t.id===n.id)||l.current.find(t=>t.id===n.id)||(f.current.push(n),h(n=>({...n,numPending:n.numPending+1})))},[]);return{add:a,stats:g}}export{i as default}; //# sourceMappingURL=use-async-queue.module.js.map