当前位置:网站首页>JS iterator generator asynchronous code processing promise+ generator - > await/async
JS iterator generator asynchronous code processing promise+ generator - > await/async
2022-07-02 12:43:00 【There is no water in the sea】
One 、 iterator
The iterator itself is an object , It can help us traverse another object 
1、 Recognize iterators
// Here is an iterator we wrote , It's an object . Help us traverse the container structure
// const iterator = {
// next: function () {
// return {
// done: true,
// value: 123,
// };
// },
// };
// Array
const names = ["a", "b", "c"];
const iterator = names[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// Console print in sequence :
// { value: 'a', done: false }
// { value: 'b', done: false }
// { value: 'c', done: false }
// { value: undefined, done: true }
console.log("================================");
// Create an iterator object to access the array
let index = 0;
const namesIterator = {
next: function () {
// return { done: false, value: "a" };
// return { done: false, value: "b" };
// return { done: false, value: "c" };
if (index < names.length) {
return {
done: false, value: names[index++] };
} else {
return {
done: true, value: undefined };
}
},
};
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
2 、 iterator function
const names = ["a", "b", "c"];
const num = [10, 20, 30];
function createArrayIterator(arr) {
let index = 0;
return {
next: function () {
if (index < arr.length) {
return {
done: false,
value: arr[index++],
};
} else {
return {
done: true, value: undefined };
}
},
};
}
const namesIterator = createArrayIterator(names);
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
const numIterator = createArrayIterator(num);
console.log(numIterator.next());
console.log(numIterator.next());
console.log(numIterator.next());
console.log(numIterator.next());
3、 Iteratable object

for-of It's the essence of iterators
// const names = ["a", "b", "c"];
// // Create an iterator object to access the array
// let index = 0;
// const namesIterator = {
// next: function () {
// if (index < names.length) {
// return { done: false, value: names[index++] };
// } else {
// return { done: true, value: undefined };
// }
// },
// };
// Iteratable object
const iteratorObj = {
names: ["a", "b", "c"],
// Satisfy the iterative Protocol
[Symbol.iterator]: function () {
let index = 0;
return {
// It needs to be changed into arrow function
next: () => {
if (index < this.names.length) {
return {
done: false, value: this.names[index++] };
} else {
return {
done: true, value: undefined };
}
},
};
},
};
console.log(iteratorObj[Symbol.iterator]);
// 1. First call iteratorObj[Symbol.iterator]
const iterator = iteratorObj[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// Second call iteratorObj[Symbol.iterator]: Generate new iterators
const iterator1 = iteratorObj[Symbol.iterator]();
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());
console.log(iterator1.next());
// 3.for...of What can be traversed must be an iteratable object
// for It's actually grammar sugar , What I do is iterator.next(), Get the object , Then take .value. When done:false, Just put value out .done by true When , Stop traversing
const obj = {
name: "chen",
age: 23,
};
for (const item of obj) {
console.log(item); //TypeError: obj is not iterable
}
4、 Native iterator object
String、Array、Map、Set、arguments object 、NodeList The collection is , Be careful : The object is not
// Built in to create iteratable objects
// 1、 Array
const names = ["a", "b", "c"];
console.log(names[Symbol.iterator]);
const iterator = names[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// 2、Map / Set
const set = new Set();
set.add(10);
set.add(100);
set.add(1000);
console.log(set[Symbol.iterator]().next());
for (const item of set) {
console.log(item)
}
console.log('-----------')
// 3、 Function arguments It's also an iterative object
function foo(x, y, z) {
for (const arg of arguments) {
console.log(arg)
}
}
foo(10, 20, 30)
5、 Application scenarios of iterator objects
// 1、for-of
// 2、 Expand operator
const names = ["a", "b", "c"];
const obj = {
name: 'chen',
age: 23
}
// You can't iterate
// for (const item of obj) {
// console.log(item)
// }
// It is worth noting that , The following is OK
// This is a ES9 A new feature in , Special processing for object deployment , It's not an iterator . adopt obj.entries()
const newObj = {
...obj }
console.log(newObj) //{ name: 'chen', age: 23 }
// This is not using iterators , Using or entries()
const {
name, age } = obj
// 3、 Deconstructive grammar , Iterators are still used , Yes. next().value
const [name1, name2, name3] = names
console.log(name1, name2, name3) // a b c
// 4、 When creating some objects
const set1 = new Set(names)
// const set2 = new Set(1334); // Report errors
// Create array
const arr1 = Array.from(names)
// 5、Promise.all
Promise.all(names).then(res => {
console.log(res) //[ 'a', 'b', 'c' ]
})
6、 Iteratability of custom classes
// class Person {
// }
// // It's not an iterative object
// const p1 = new Person();
// const p2 = new Person();
// Case study : Create a teacher class , The created objects are all iteratable objects
class Classroom {
constructor(address, name, students) {
this.address = address;
this.name = name;
this.students = students;
}
entry(newStudent) {
this.students.push(newStudent);
}
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.students.length) {
return {
done: false, value: this.students[index++] };
} else {
return {
done: true, value: undefined }
}
}
}
}
}
const classroom = new Classroom(' Beijing ', ' Computer classroom ', ['zhangsan', 'lisi', 'wangwu']);
classroom.entry('jianren')
// classroom It's not an iterative object , If you want to iterate , You need to add [Symbol.iterator]
for (const item of classroom) {
console.log(item)
}
// Next output :
// zhangsan
// lisi
// wangwu
// jianren
// If it is function, It's the same
// function Person () {
// }
// Person.prototype[Symbol.iterator] = function(){
// }
Two 、 generator
1、 What is a generator - Generator function

// Generator function , Yes * , adopt yield Control the code execution process , The return value is an iterator
function* foo() {
console.log(' The function starts executing ~')
// Pause during code execution
// First code
const value = 100
console.log(value)
yield
// Second code
const value1 = 200
console.log(value1)
yield
// The third code
const value2 = 300
console.log(value2)
yield
console.log(' End of function execution !')
}
// So call , One line of code will not execute
foo()
// When we call the generator function , Will return a generator ( Special iterators )
const generator = foo()
// Execute the first code
generator.next()
// Execute the second code
generator.next()
// Execute the third code
generator.next()
2、 Execution process of generator function
// When you meet yield Only pause the execution of the function
// When you meet return When , The generator stops executing
function* foo() {
console.log(' The function starts executing ~')
const value = 100
console.log(value)
// return value, Stopped. . If you want to go back , Follow directly behind
yield value * 200
const value1 = 200
console.log(value1)
yield
const value2 = 300
console.log(value2)
yield
console.log(' End of function execution !')
}
foo()
const generator = foo()
// generator.next()//100
// generator.next()//200
// generator.next()//300
// generator.next()
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
// In turn, print :
// { value: undefined, done: true }
// { value: undefined, done: true }
// { value: undefined, done: true }
// { value: undefined, done: true }
// What is returned is the iterator :
// 100
// { value: undefined, done: false }
// 200
// { value: undefined, done: false }
// 300
// { value: undefined, done: false }
// End of function execution !
// { value: undefined, done: true }
3、 Generator's next Pass parameters
function* foo() {
console.log(' The function starts executing ~')
const value = 100
console.log(value)
const n = yield value
const value1 = n * 10
console.log(value1)
yield
const value2 = 300
console.log(value2)
yield
console.log(' End of function execution !')
}
foo()
// 1. On generator next Method can pass parameters
const generator = foo()
console.log(generator.next())
console.log(generator.next(10))
console.log(generator.next())
console.log(generator.next())
4、 Generators replace the use of iterators 1
// Generator replaces iterator
function* createArrayIterator(arr) {
let index = 0;
// Writing a :
// yield arr[index++]; //{ done: true, value: undefined };
// yield arr[index++];
// yield arr[index++];
// Write two :
// yield 'a';
// yield 'b';
// yield 'c';
// Write three :
// for (const item of arr) {
// yield item;
// }
// Write four : yield* Iteratable object
yield* arr
// return {
// next: function () {
// if (index < arr.length) {
// return {
// done: false,
// value: arr[index++],
// };
// } else {
// return { done: true, value: undefined };
// }
// },
// };
}
const names = ["a", "b", "c"]
const namesIterator = createArrayIterator(names);
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
5、 Generators replace the use of iterators 2
// Generator replaces iterator
function* createArrayIterator(arr) {
let index = 0;
yield* arr;
}
// 2. Create a function , This function can iterate over a range of numbers
// 10 20
// function createRangeIterator(start, end) {
// // Writing a :
// let index = start;
// return {
// next: function () {
// if (index < end) {
// return {
// done: false,
// value: index++,
// };
// } else {
// return { done: true, value: undefined };
// }
// },
// };
// }
function* createRangeIterator(start, end) {
// Writing a :
let index = start;
while (index < end) {
yield index++;
}
}
const iterator = createRangeIterator(10, 20);
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// Output is as follows :
// { done: false, value: 10 }
// { done: false, value: 11 }
// { done: false, value: 12 }
// { done: false, value: 13 }
6、 Processing scheme of asynchronous code
function requestData(url) {
// The code for asynchronous requests will be put into executor in
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(url);
}, 1000);
});
}
// 1. First option : Multiple callbacks
// Back to hell
// requestData('chen').then(res => {
// requestData(res + '/aaaa').then(res => {
// requestData(res + '/bbbb').then(res => {
// console.log(res);
// })
// })
// })
// 2. Second option : Promise in then To solve the problem
// requestData('chen').then(res => {
// return requestData(res + '/aaaa')
// }).then(res => {
// return requestData(res + '/bbbb');
// }).then((res) => {
// console.log(res);
// })
// 3. The third option : Promise + generator Realization ( Do it manually )
// function* getData() {
// const res1 = yield requestData("chen");
// const res2 = yield requestData(res1 + "/aaaa");
// const res3 = yield requestData(res2 + "/bbbb");
// console.log(res3);
// }
// const generator = getData();
// generator.next().value.then((res) => {
// // console.log(res); // If you want to get this res, Need to execute the next next(), And send the value back
// generator.next(res).value.then((res) => {
// // console.log(res);
// generator.next(res).value.then((res) => {
// console.log(res);
// });
// });
// });
// 3. The third option : Promise + generator Realization ( Automatic execution )
// function execGenerator(getFn) {
// const generator = getFn();
// // Using recursion
// function exec(res) {
// const result = generator.next(res);
// if (result.done) {
// return result.value;
// } else {
// result.value.then(res => {
// exec(res);
// })
// }
// }
// exec();
// }
// execGenerator(getData);
// 4. The fourth option : await/async
// function* getData() {
// const res1 = yield requestData("chen");
// const res2 = yield requestData(res1 + "/aaaa");
// const res3 = yield requestData(res2 + "/bbbb");
// console.log(res3);
// }
// It's actually yield The grammar sugar of
async function getData() {
const res1 = await requestData("chen");
const res2 = await requestData(res1 + "/aaaa");
const res3 = await requestData(res2 + "/bbbb");
console.log(res3);
}
getData()
边栏推荐
- Enhance network security of kubernetes with cilium
- Browser node event loop
- AI mid stage technology research
- Dijkstra AcWing 850. Dijkstra求最短路 II
- bellman-ford AcWing 853. 有边数限制的最短路
- 软件测试面试题-2022年大厂面试题合集
- 哈希表 AcWing 841. 字符串哈希
- PR 2021 quick start tutorial, learn about the and functions of the timeline panel
- Direct control PTZ PTZ PTZ PTZ camera debugging (c)
- 一些突然迸发出的程序思想(模块化处理)
猜你喜欢

线性DP AcWing 895. 最长上升子序列

LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY

Lekao.com: experience sharing of junior economists and previous candidates in customs clearance

堆 AcWing 838. 堆排序

8 examples of using date commands

bellman-ford AcWing 853. Shortest path with side limit

js1day(输入输出语法,数据类型,数据类型转换,var和let区别)

VLAN experiment

Deep Copy Event bus

移动式布局(流式布局)
随机推荐
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
Mui WebView down refresh pull-up load implementation
包管理工具
JS8day(滚动事件(scroll家族),offset家族,client家族,轮播图案例(待做))
堆 AcWing 838. 堆排序
Efficiency comparison between ArrayList and LinkedList
Linear DP acwing 896 Longest ascending subsequence II
. Net wechat message template push
8A 同步降压稳压器 TPS568230RJER_规格信息
js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
Rust search server, rust quick service finding tutorial
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
H5 to app
Docker compose configuration mysql, redis, mongodb
Embedded Software Engineer career planning
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
Dijkstra AcWing 850. Dijkstra求最短路 II
Bom Dom
[ybtoj advanced training guidance] cross the river [BFS]
spfa AcWing 852. SPFA judgement negative ring