如何使用"等待"对于发电机功能是ES6?

时间:2017-06-18 10:01:47

标签: javascript reactjs react-native es6-promise ecmascript-2017

问题

我很好奇是否可以在现代ES2017中的异步 / 等待上下文中使用生成器功能。 (该应用程序是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的结果。如何在此上下文中使用生成器函数?

1 个答案:

答案 0 :(得分:1)

从它的外观来看,它的协同作用(一些)承诺。假设真实结果只是协程的最后结果,并且您无法更改生成器代码,您可以迭代生成器并等待所有内容 - 将等待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
}
相关问题