1

问题

我很好奇,如果有可能消耗在一个发电机功能全异步/等待现代ES2017内上下文。 (应用程序是一个阵营,本机应用程序)如何使用“等待”发电机功能是ES6?

这是我的代码,我想打电话给发生器功能:

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的结果。我如何在这种情况下使用生成器函数?

+0

gen = loadProduct();等待gen.next(); –

+0

显然.next()为loadProduct-Function中的每个“yield”语句提供了许多结果(在里面有很多yield-statements,比在问题中显示的多) – delete

+0

我还没有得到用例吗?发生器返回什么?承诺? –

回答

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 
} 
+0

为什么要在这里使用'await'?没有它,它应该做同样的事情。 – trincot

+0

因为它的承诺 - 请参阅'调用(loadProductFromWeb ...' –

+0

OP说它返回承诺? – trincot