组成值的生成器生产者

Composing generator producer of values

我怎样才能组成一个生产者生成器,用另一个生成器从外部获取值?如果 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}
// ...

要获取发送到 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