Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 933
delete Avatar asked Jun 18 '17 10:06

delete


People also ask

Can you await a generator function?

Description. An async generator function combines the features of async functions and generator functions. You can use both the await and yield keywords within the function body.

Is async await implemented with generators?

In this article I will apply those concepts and show how we can use generators to build something similar to async/await. In fact, async/await is implemented using generators and promises.

Can generator function be async?

The AsyncGenerator object is returned by an async generator function and it conforms to both the async iterable protocol and the async iterator protocol. Async generator methods always yield Promise objects.

How do you use await in a function?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


1 Answers

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
}
like image 152
Meirion Hughes Avatar answered Sep 30 '22 16:09

Meirion Hughes