Javascript 如何使用;等待“;发电机的功能是ES6? 问题
我很好奇,在现代ES2017的异步/等待环境中,是否可以使用生成器-函数。(该应用程序是React本机应用程序) 这是我想调用生成器函数的代码:Javascript 如何使用;等待“;发电机的功能是ES6? 问题,javascript,reactjs,react-native,es6-promise,ecmascript-2017,Javascript,Reactjs,React Native,Es6 Promise,Ecmascript 2017,我很好奇,在现代ES2017的异步/等待环境中,是否可以使用生成器-函数。(该应用程序是React本机应用程序) 这是我想调用生成器函数的代码: class ProductViewComponent extends Component { async componentDidMount() { const result = await loadProduct(...) console.log(result) // Gives: *Generator* and not th
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;
}
具体问题是:
据我所知,我可以使用
wait
等待承诺的结果。在这种情况下如何使用生成器函数?从外观上看,这是一个产生(一些)承诺的协同程序。假设实际结果只是协同程序的最后一个结果,并且您不能更改生成器代码,那么您可以迭代生成器并等待一切—承诺将被等待,未定义的将被忽略
async componentDidMount() {
const resultGenerator = loadProduct(...);
let result;
for (let task of resultGenerator) {
result = await task ;
}
console.log(result); // should be last result of coroutine
}
gen=loadProduct();等待下一任将军();显然,.next()为loadProduct函数中的每个“yield”语句提供了许多结果(其中有许多yield语句,比问题中显示的要多),我仍然不明白这个用例?发电机返回什么?承诺?可能重复您为什么在此处使用
wait
?如果没有它,它也应该这样做。因为它会产生承诺-请参阅调用(loadProductFromWeb…
OP在哪里说它会返回承诺?这是一个有根据的猜测,因为“loadProductFromWeb”