发电机和设定值/完成产量

时间:2016-03-27 22:08:18

标签: javascript ecmascript-6

如果我创建一个自定义生成器,我可以设置我认为合适的值/完成,但我相信我在这里使用es6生成器出错了,因为我似乎无法设置我想要的值/完成。当我设置一些东西时,它全部进入“值”,但生成器的返回“完成:假” - 我试图强制“完成:真实”

var A = [
    {id: 1, page: 'page one'},
    {id: 2, page: 'page two'},
    {id: 3, page: 'page three'},
    {id: 4, page: 'page four'},
  ]
function* gen(iteree) {
    let input = yield null
    while(true) 
      input = yield iteree(input) ? iteree(input) : { done: true}
}

// this will be built out more, just showing a 
// passing of a function here
let inter = (a) => { 
       return A[a]
}

let c = gen(inter)
    console.log(c.next())
    console.log(c.next(4)) // <-- **I want this to yield {value: null, done: true}**

但它会产生:{value:{done:true},done:false}

2 个答案:

答案 0 :(得分:1)

“强制done”将由return完成。在发电机中时

yield 4;
// {value: 4, done: false}

return 4;
// {value: 4, done: true}

答案 1 :(得分:1)

以下是我在您的代码中创建您正在寻找的答案。

    var A = [
    {id: 1, page: 'page one'},
    {id: 2, page: 'page two'},
    {id: 3, page: 'page three'},
    {id: 4, page: 'page four'},
  ]
function* gen(iteree) {
    let input = yield null
    while(input <= A.length) {
      if(iteree(input)){
        yield iteree(input) 
      }else{
        return null;
      }
   }
}

// this will be built out more, just showing a 
// passing of a function here
let inter = (a) => { 
       return A[a]
}

let c = gen(inter)
console.log(c.next())
console.log(c.next(4))