1

I am trying to understand how Generators can work with promises and would like to know how to return the resolved value of a promise in a Generator.

The following code contains an Unexpected identifier error. I think this is because the yield is in the .done() callback but I am not sure. How can I get the result of the promise when I call next() on the generator?

Here is my code:

function *genPromise(url) {
 $.getJSON(urlArray)
    .done( res => {
     yield res.data.children[1].data.url;
  });
}

var url = 'https://www.reddit.com/r/reddits.json';

var x = genPromise(url)

console.log(x.next());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mdd
  • 4,140
  • 12
  • 45
  • 70
  • 3
    Neither generators nor promises allow to make asynchronous tasks synchronous. – Bergi Mar 01 '16 at 19:19
  • 1
    You need to `yield` the promise. You cannot use `yield` in a callback. You're not supposed to use callbacks at all. You need to pass your generator to a runner function such as `co`. – Bergi Mar 01 '16 at 19:19
  • 1
    Maybe have a look at [Understanding code flow with yield/generators](http://stackoverflow.com/q/23551418/1048572) and http://davidwalsh.name/async-generators – Bergi Mar 01 '16 at 19:21

0 Answers0