How to use "await" for a generator function is ES6?
Asked Answered
D

1

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?

Diversification answered 18/6, 2017 at 10:1 Comment(4)
gen = loadProduct(); await gen.next();Collum
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)Diversification
i still dont get the usecase? What does the generator return? Promises?Collum
Possible duplicate of Migrating from Generators to Async/AwaitSutton
M
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
}
Marvel answered 18/6, 2017 at 10:26 Comment(4)
Why would you use await here? It should do the same without it.Manicotti
Because its yielding promises - see call(loadProductFromWeb...Marvel
Where does the OP say it returns promises?Manicotti
Its an educated guess due to "loadProductFromWeb"Marvel

© 2022 - 2024 — McMap. All rights reserved.