Home > Enterprise >  Javascript generator function?
Javascript generator function?

Time:07-25

Am I stupid of what does this generator function in Javascript do:

function* generator() {
  let hook, waiting = yield new Promise(resolve => {
    function* wait() { resolve(yield) }
    hook = wait();
    hook.next();
  });
  hook.next(waiting);
}

Source: https://github.com/padlet/async-semaphore

CodePudding user response:

This one took a couple minutes to process.

The resolve(yield) part actually gives the promise the value of the 2nd next() call's params (waiting). I think this could be made in a cleaner way with just 1 generator.

generator.next() on MDN

The result is:

let g = generator()
g.next().value.then(console.log) // returns a pending promise
g.next("test")                   // returns nothing important but
// the then callback logs "test"

So you can put as many callbacks on the first call of generator.next().value, and you let them all go on the second, while also passing in a param to the first which you can chain in the regular promise fashion.

  • Related