ES6 如何为生成器函数使用“await”?

del*_*ete 5 javascript reactjs es6-promise react-native ecmascript-2017

问题

我很好奇是否可以在现代 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
  }

}
Run Code Online (Sandbox Code Playgroud)

该函数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;
}  
Run Code Online (Sandbox Code Playgroud)

具体问题:

据我所知,我可以await用来等待 Promises 的结果。在这种情况下如何使用生成器函数?

Mei*_*hes 1

从表面上看,它是一个产生(一些)承诺的协程。假设真正的结果只是协程的最后一个结果,并且您无法更改生成器代码,您可以迭代生成器并等待一切 - Promise 将被等待,未定义将被忽略。

async componentDidMount() {
  const resultGenerator = loadProduct(...);

  let result;

  for (let task of resultGenerator) {
    result = await task ;
  }

  console.log(result); // should be last result of coroutine
}
Run Code Online (Sandbox Code Playgroud)