关于ecmascript:ES6新增语法六Generator函数详解

33次阅读

共计 1374 个字符,预计需要花费 4 分钟才能阅读完成。

上篇文章《ES6 新增语法 (五)——Promise 详解》咱们介绍 Promise,Promise 一旦执行就无奈暂停和勾销,所以 ES6 引入了 Generator 函数,能够通过 yield 关键字,把函数的执行流程挂起,能够扭转执行流程。

什么是 Generator 函数?

Generator 次要是异步编程,用来封装异步工作,是一个异步工作的容器,能够让函数依照咱们指定的时候执行或者暂停。

应用语法:

function *name(){

yield; // 须要暂停的时候加 yield

yield;

}

const p = name();

p.next() // 调用函数,执行到第一个 yield 处进行

p.next() // 从上一个 yeild 开始执行,到下一个 yield 处为止

Generator 与一般函数区别

1> 定义函数的时候比一般函数多了一个 * 号。

2> 调用的时候,一般函数名后加圆括号间接调用,而 Generator 并不执行,返回的也不是函数运行后果,而是指向外部的状态的指针对象,必须调用遍历器对象的 next() 办法,使得指针移向下一个状态。每次调用 next,指针就会从上一次停下的中央开始执行到下一个 yield。

3> 一般函数是无奈暂停的,但 Generator 函数是分段执行的,yield 是暂停标记,而 next() 能够复原执行。

generator 实例如下:

function *show(){console.log('1')
 yield;
 console.log('2')
}
const p = show();
p.next(); // 执行第一个 yield 之前内容,打印 1
p.next(); // 执行 yield 之后内容,打印 2 

yield 特点
1> 能够传参数,只能传一个参数

function *chuancan(){console.log('1')
 let a = yield;
 console.log('a',a)//12
}
const gen = chuancan();
gen.next()
gen.next(12)

2> 返回值

function *fanhui(){console.log('1');
 yield 55;
 console.log('2');
}
let fh = fanhui()
let res1 = fh.next()
console.log(res1) //{value: 55, done: false}
let res2 = fh.next()
console.log(res2) //{value: undefined, done: true}

generator 函数中也能够增加 return

function *show(){console.log('1')
 yield 55;
 console.log(2);
 return 89;
}
let gen = show();
let res1 = gen.next();
console.log(res1) //{value: 55, done: false}
let res2 = gen.next();
console.log(res2) //{value: 89, done: true}

return 办法

return 办法返回给定值,并完结遍历 generator 函数。

return 办法提供参数时,返回该参数,不提供时,返回 undefined。

Generator 函数长处

Generator 函数是 ES6 提供的一种异步编程解决方案,解决了两大问题:

  • 回调天堂
  • 异步流控

正文完
 0