0

I can't figured out why I get .log "after" the same time as "before", without the delay. What am I doing wrong?

function *sequence () {
    yield console.log("before")        
    yield new Promise(resolve => setTimeout(resolve, 5000))
    yield console.log("after")
}

for (const item of sequence) {
   console.log("---")
}
Andrew
  • 695
  • 1
  • 8
  • 21
  • 1
    Because you aren't waiting for the Promise to resolve..? – CertainPerformance May 24 '20 at 18:21
  • @CertainPerformance That's a very wide net to catch something as a duplicate :) – Icepickle May 24 '20 at 18:24
  • 1
    You could have a look at enabling an [async generator](https://javascript.info/async-iterators-generators) instead, for example like this: https://jsfiddle.net/f6dnqthp/ – Icepickle May 24 '20 at 18:29
  • @jay_dtr are you confusing `yield` with `await`? The former doesn't wait for anything. It might help to `console.log` the `item` to see what's going on. – Bergi May 24 '20 at 18:39
  • @Icepickle I don't think that's what the OP wants. – Bergi May 24 '20 at 18:39
  • @Bergi, who knows, he just got a large net thrown around him that might not be what he is looking for either, he presents a generator, wants to use some promises, so he kinda has to use an async generator to solve it, it might be dumbed down code from the OP – Icepickle May 24 '20 at 19:22
  • @Bergi even his title contains generator, I think this dupe call is a duplicator badge hunt, seeing promise but not looking at the question – Icepickle May 24 '20 at 23:41
  • @Icepickle There is no such badge? And even if the duplicate targets are badly chosen, I don't think the question should be reopened as it's unclear what the OP wants. – Bergi May 25 '20 at 09:44

1 Answers1

0

It might be because you do not wait for the promise to resolve. You need to await the promise you return at the second yield

Yooooomi
  • 895
  • 1
  • 8
  • 20