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