6

The issue

I'm curious if it would be possible to consume a generator-function in async/await context within modern ES2017. (The application is a React-native-application)

This is my code where I want to call the generator function:

class ProductViewComponent extends Component {

  async componentDidMount() {
    const result = await loadProduct(...)
    console.log(result)  // Gives: *Generator* and not the final result
  }

}

The function loadProduct() was imported from another file and is defined as follows:

export function * loadProduct(id) {

   let product = yield select(productByIdSelector(id));
   if(!product) {
      // ... yield this
      // ... yield that
      // ... finally:
      product = yield call(loadProductFromWeb, id) 
   }
   return product;
}  

The concrete question:

As far as I know I can use await to await results from Promises. How can I use generator functions in this context?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
delete
  • 18,144
  • 15
  • 48
  • 79
  • gen = loadProduct(); await gen.next(); – Jonas Wilms Jun 18 '17 at 10:08
  • apparently the .next() gives many results for each "yield"-statement within the loadProduct-Function (there are many yield-statements inside, more than displayed in the question) – delete Jun 18 '17 at 10:17
  • i still dont get the usecase? What does the generator return? Promises? – Jonas Wilms Jun 18 '17 at 10:34
  • Possible duplicate of [Migrating from Generators to Async/Await](https://stackoverflow.com/questions/41579282/migrating-from-generators-to-async-await) – Estus Flask Jun 18 '17 at 11:07

1 Answers1

1

From the looks of it its a coroutine yielding (some) promises. Assuming the real result is simply the last result of the coroutine, and you cannot change the generator code, you can iterate the generator and await everything - Promises will be awaited and undefineds will be ignored.

async componentDidMount() {
  const resultGenerator = loadProduct(...);

  let result;

  for (let task of resultGenerator) {
    result = await task ;
  }

  console.log(result); // should be last result of coroutine
}
Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122