Generator functions
Author: egriff38Created Feb 26, 2020Updated Jul 25, 2025
Hello!
I am a new user to comlink and am thrilled to begin integrating it into my projects as the primary way to communicate between the main thread and web workers. My question is, does comlink provide any way of working with generator functions?
My base example is as follows:
//////////// worker.js ///////////////
const fibGen = function*(max: number) {
if(max > 0 ) yield 1
if(max > 1 ) yield 1
let a=1, b=1
for(let i=2; i<max; i++) {
const c = a
a = b
b = a+c
yield b
}
}
Comlink.expose({fibGen})
///////// main.js ////////////
const wrapped = Comlink.wrap(new Worker("./worker.js"))
// cannot serialize because the return value is a generator
const gen = await wrapped.fibGen(50)
// throws saying cannot use as an async generator
for await(i of wrapped.fibGen(50)) {
console.log(i)
}I know there are other API methods available with Comlink, I'm just a little green on the best way to go about using them in this case.
Thanks in advance! This is my fourth stopping point after workerize-loader, workerize, and comlink-loader, and has been by far the easiest implementation with my existing setup.
Source: GoogleChromeLabs/comlink