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;
}
As far as I know I can use await
to await results from Promises. How can I use generator functions in this context?
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With