yield需要配合Generator使用。
我总结了一下,一共两个特性。

  1. 直接调用Generator函数时不会执行任何操作需要配合next()使用
  2. 在Generator函数中会分段执行。
    一个简单的小栗子,解释的明明白白。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let go = function* (x) {
console.log('1', x);
let a = yield x;
console.log('3', x);

console.log('4', a);

let b = yield (x + 1) + a;

return a + b;
}
go(10);
let g = go(10);
console.log(g.next());
console.log(g.next(100));
console.log(g.next(1000));

打印输出为

image.png

运行顺序:

  1. go(10)
    没有执行任何操作

  2. console.log(g.next());
    执行了

    1
    2
    console.log('1', x);
    let a = yield x;

    并且在let a = yield x;处暂停住,并且返回yield后面的值x,并放入返回对象的value中。
    yield会返回一个对象{value:1,done:false}
    value表示yield后面的值,done表示是否已经完成了Generator函数。
    xgo(10)传入了10所以打印出来前两部是 10{value:10,done:false}

  3. console.log(g.next(100));
    继续执行

    1
    2
    3
    4
    let a = yield x;
    console.log('3', x);
    console.log('4', a);
    let b = yield (x + 1) + a;

    let a = yield x;处继续向下执行,a = yield x的值从g.next(100)传入100,因此a=100
    x值不变依然为10
    打印 3 104 100
    执行到 let b = yield (x + 1) + a;,准确的说应该是yield (x + 1) + a
    返回{value: 111, done: false}

  4. console.log(g.next(1000));
    执行最后一个yield
    b等于g.next(1000)传入的1000
    Generator函数返回 a+b等于1100
    所以答应{value: 1100, done: true}

仔细看完,yield基础用法没问题了。