TPReal
TPReal

Reputation: 1585

Asynchronously working generator function

I want to have a JS generator function that returns a series of some stuff, let's say its suggestions for dinner. It knows names of some dishes, but if I don't like any of them, it will need to fetch more suggestions from a remote server. So I'd like this to work:

const dishSuggestions = function* (){
  yield "pancakes";
  yield "pizza";
  fetchMealSuggestions().then(suggestions => {  // Or even better await.
    for (const suggestion of suggestions)
      yield suggestion;
  });
};

This won't work obviously because I cannot yield from an inner function. So my question is: how to get that behaviour? Can I? Or is this the wrong tool?

Upvotes: 1

Views: 73

Answers (1)

nem035
nem035

Reputation: 35501

Theoretically, what you want in this situation is an async generator that contains an async iterator.

Here's how that would look:

// Note the * after "function"
async function* dishSuggestions() {
  yield "pancakes";
  yield "pizza";

  // async iteration: yield each suggestion, one after the other
  for await (const meal of fetchMealSuggestions()) {
    yield meal;
  }
}

async function logDishes() {
  for await (const dish of dishSuggestions()) {
    console.log(dish);
  }  
}

logDishes();

Here's a working transpilled demo with Babel.

Note that fetchMealSuggestions must also return an async iterator for the async iteration to work.

That being said, this is still a brand-new feature that just started shipping with each browser.

More details

For now, take a look at the question Bergi recommended in the comments.

Upvotes: 2

Related Questions