异步编程-generator

77 阅读1分钟

generator是一个状态机,封装了异步状态,解决了异步编程。 generator有两个特征。1.function name之间有个*。2.内部有yield.yield定义不同的内部状态。

function* hello(){
yield 'hello';
 yield 'world';
 return 'ending';}
var h=hello();
console.log(h.next()) //{ value: "hello", done: false }
console.log(h.next()) // world { value: "world", done: false }
console.log(h.next()) //ending { value: "ending", done: true }


function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
 return (x + y + z);}
 
var a = foo(5); a.next() 
// Object{value:6, done:false}  参数55+1=6
a.next() // Object{value:NaN, done:false},没有参数。y=2*undefined
a.next() // Object{value:NaN, done:true}

var b = foo(5);b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }   y=2*12=24;  yield(24/3)= 8
b.next(13)   13+5+24