Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript generator function?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading