2016-01-23 12 views
3

您可以從封閉收益率?ES6/ES2015在封閉收益率內的函數*

// I want the following to work but instead I get: 
// Uncaught SyntaxError: missing) after argument list(…) 

function* test() { 
    yield 1; 
    [2,3].map(x => yield x); 
    yield 4; 
} 

var gen = test(); 
console.log(gen.next().value); // 1 
console.log(gen.next().value); // 2 
console.log(gen.next().value); // 3 
console.log(gen.next().value); // 4 
+0

只是不,你不能。 – Bergi

+0

當閉包不是從「內部」(無論何種定義)被調用時,閉包會做什麼? – Bergi

回答

1

您應該使用yield*的控制研究傳遞到其他迭代對象 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/yield*

也試圖yield非發電機的功能,你不能裏面。只需使用return

function* test() { 
    yield 1; 
    yield* [2,3].map((x) => {return x}); 
    yield 4; 
} 

var gen = test(); 
console.log(gen.next().value); // 1 
console.log(gen.next().value); // 2 
console.log(gen.next().value); // 3 
console.log(gen.next().value); // 4 
+2

請注意,在這種情況下,'map'會被急切地評估到數組中,我想這不是OP的意思。 – Bergi