组成生成器生成器的值

时间:2015-03-31 21:37:49

标签: javascript generator ecmascript-6

如何组合生成器生成器,使用另一个生成器从外部获取值?如果producer在生成器中产生一个值,那么它就可以工作,但是当我发送一个next的值时,我得到undefined。有没有办法做到这一点?

function* producer() {
    while (true) {
        yield // want to send values here
    }
}

function* take(n, gen) {
    var i = 0
    for (var x of gen) {
        if (i <= n) {
            yield x // want the value sent to the producer
            i += 1
        } else {
            break
        }
    }
}

var prod = producer()
var res = take(5, prod)

// How can I send values to the producer
// and make the result yield those values?

res.next() // init
console.log(res.next(1)) // {value: undefined, done: false}
console.log(res.next(2)) // {value: undefined, done: false}
// ...

// I want to get
// {value: 1, done: false}
// {value: 2, done: false}
// ...

1 个答案:

答案 0 :(得分:1)

要获取发送到next()的值,您应该使用yield返回的结果。我不太确定你的最终目标是什么,但这是修改过的示例:

let producer = function*() {
    var nextResult = undefined;
    while(true) {
        nextResult = yield nextResult;
        console.log("produce " + nextResult);
    }
}

let take = function*(number, items) {         
    var count = 0;
    var item = undefined;
    while (count <= number) {
        items.next(item);
        item = yield item;
        console.log("take " + item);
        count += 1;
    }
}

var res = take(2, producer())

res.next() // init
console.log('result ' + res.next(3).value)
console.log('result ' + res.next(2).value)

输出:

take 3
produce 3
result 3
take 2
produce 2
result 2

ES6 fiddle link