16.Generator函数的语法

生成器的用法

// generator函数 可以通过yield关键字,将函数挂起,为改变执行流提供了可行性
	// 它与普通函数的区别
	// 1.function后面 函数名之前有个*
	// 2.只能在函数内部使用yield表达式,让函数挂起
	function *gen(){
		console.log(0)
		let x = yield 1
		console.log('1',x)   //1 20
		let y = yield 2
		console.log('2',y)   //2 30
		yield 3
		return x + y	
	}
	let a = gen()
	console.log(a.next(10)) 
	// 0
	// {value:'1',done:false}
	console.log(a.next(20)) 
	// 1 20
	// {value:'2',done:false}
	console.log(a.next(30)) 
	// 2 30
	// {value:'3',done:false}
	console.log(a.next(40)) 
	// {value:'50',done:true}
	
	//	使用场景:为不具备Interator接口的对象提供了遍历操作
	function* objectEntries(obj){
		// 获取对象的所有的key保存到数组[name,age]
		const propKeys = Object.keys(obj);
		for(const propkey of propKeys){
			yield [propkey,obj[propkey]]
		}
	}
	const obj = {
		name:'alan',
		age:18
	}
	console.log(obj);
	// {name: 'alan', age: 18}
	for(let [key,value] of objectEntries(obj)){
		console.log(`${key},${value}`);
	}
	// name,alan
	// age,18

 

生成器的应用

// 生成器generator的应用 异步代码同步化,解决ajax的回调地狱
	function *gen(){
		loadShow()
		yield getData()
		loadHide()
	}
	let  alan = gen()
	alan.next()
	
	// 显示Loading -> 请求数据 -> 关闭Loading
	function loadShow(){
		console.log('显示Loading')
	}
	function getData(){
		setTimeout(()=>{
			console.log('请求数据')
			alan.next()
		},1000)
		
	}
	function loadHide(){
		console.log('关闭Loading')
	}
	// 显示Loading
	// 请求数据
	// 关闭Loading

 

1.简介

Generator 函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同。

执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。

形式上,Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)。

 

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

var hw = helloWorldGenerator();

上面代码定义了一个 Generator 函数helloWorldGenerator,它内部有两个yield表达式(helloworld),即该函数有三个状态:hello,world 和 return 语句(结束执行)。

 

2.next方法的参数

 

3.for...of循环

 

4.Generator.prototype.throw()

 

5.Generator.prototype.return()

 

6.yield* 表达式

 

7.作为对象属性的Generator函数

 

8.Generator函数的this

 

9.含义

 

10.应用

 

posted @   泠风lj  阅读(136)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示