问题
我很好奇是否可以在现代 ES2017 中的 async/await 上下文中使用 generator 函数。 (该应用程序是一个 React-native-application)
这是我要调用生成器函数的代码:
class ProductViewComponent extends Component {
async componentDidMount() {
const result = await loadProduct(...)
console.log(result) // Gives: *Generator* and not the final result
}
}
函数loadProduct()
是从另一个文件导入的,定义如下:
export function * loadProduct(id) {
let product = yield select(productByIdSelector(id));
if(!product) {
// ... yield this
// ... yield that
// ... finally:
product = yield call(loadProductFromWeb, id)
}
return product;
}
具体问题:
据我所知,我可以使用 await
来等待 Promises 的结果。我如何在这种情况下使用生成器函数?
最佳答案
从外观上看,它是一个产生(一些) promise 的协程。假设真正的结果只是协程的最后一个结果,并且您不能更改生成器代码,您可以迭代生成器并等待一切 - Promises 将被等待,undefined 将被忽略。
async componentDidMount() {
const resultGenerator = loadProduct(...);
let result;
for (let task of resultGenerator) {
result = await task ;
}
console.log(result); // should be last result of coroutine
}
关于javascript - 如何将 "await"用于生成器函数是 ES6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613830/