To cook a function into an asynchronous one use asyncWorker.cook
const{cook}=newAsyncWorker()
constasyncFibo=cook(()=>n=>{
if(n<=0)returnNaN
let[first,second]=[0,1]
while(--n)[first,second]=[second,first+second]
returnfirst
})
constres=awaitasyncFibo(5)
console.log(`5th fibonnaci number is ${res}`)
functioncook<T,Sextendsany[],Uextendsany[]>(
func:(...args:S)=>(...args:U)=>T,
...args:S
):(...args:U)=>Promise<T>
track
To track progress of a task use asyncWorker.track
const{track}=newAsyncWorker()
consttracker=track((tick,n)=>{
letfact=1
for(leti=1;i<=n;i++){
fact*=i
tick(i/n)
}
returnfact
},15)
tracker.tick(progress=>console.log(`the factorial is ${progress*100}% done!`))
console.log(`the result is ${awaittracker.result}`)
functiontrack<T,Sextendsany[]>(
func:(tick:(progress:number)=>void,...args:S)=>T,
...args:S
):{
result:Promise<T>
tick:(ticker:(progress:number)=>void)=>void
}
kill
Once you're done using, you can kill it
constasync=newAsyncWorker()
async.task(/* doing something */)
async.kill()
common mistakes
Because web workers exist in a different thread the passed function does not have access to your current context variables. To pass in variables please add them as additional parameters and accept them in your functions. This will not work:
//...
constfrom=10
constto=1000000
constprimes=awaittask(()=>{
console.log(from)// error during worker runtime: 'from' is not defined
console.log(to)// error during worker runtime: 'to' is not defined
})
//...
Do instead:
//...
constfrom=10
constto=1000000
constprimes=awaittask(
(from,to)=>{
console.log(from)// :)
console.log(to)// :)
},
from,
to
)
//...
Some types are not transferable. Meaning you cannot send them to or recieve from a web worker. Notably functions are not transferable. The following will not work: