0

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

12
  • Did I phrase my question wrong? Commented Jul 25, 2022 at 11:14
  • 1
    There is a comment in the github repo explaining the code (index.js at line 102) Commented Jul 25, 2022 at 11:18
  • doesn't explain the syntax of how this dude is assigning two variables from one initialization Commented Jul 25, 2022 at 11:23
  • 4
    You misread the assignment. It is just short for let hook; let waiting = Commented Jul 25, 2022 at 11:25
  • 1
    @NickParsons Maybe it has to do with the referrer. So, no direct link (hotlinking) but it can be reached if you use github.com/padlet/async-semaphore . Same error if I try github.com/padlet/async-semaphore/blob/master/index.js directly, or if I go through the link and refresh the browser tab. Commented Jul 25, 2022 at 11:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah shit I was scratching my head for a second (still am), but this makes it more clear thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.