当前位置:网站首页>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()
边栏推荐
- In development, why do you find someone who is paid more than you but doesn't write any code?
- Bom Dom
- Introduction to CPU instruction set
- 2.6 using recursion and stack - [tower of Hanoi problem]
- bellman-ford AcWing 853. 有边数限制的最短路
- Interview with meituan, a 34 year old programmer, was rejected: only those under the age of 30 who work hard and earn little overtime
- async/await 异步函数
- JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
- Linear DP acwing 895 Longest ascending subsequence
- Use MySQL events to regularly perform post seven world line tasks
猜你喜欢

Async/await asynchronous function

染色法判定二分图 AcWing 860. 染色法判定二分图

spfa AcWing 851. spfa求最短路

Linear DP acwing 898 Number triangle

防抖 节流

Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand

线性DP AcWing 899. 编辑距离

移动式布局(流式布局)

PR 2021 quick start tutorial, learn about the and functions of the timeline panel

通过反射执行任意类的任意方法
随机推荐
包管理工具
Docker compose configuration mysql, redis, mongodb
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
Find the common ancestor of any two numbers in a binary tree
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
Linear DP acwing 895 Longest ascending subsequence
Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
[I'm a mound pytorch tutorial] learning notes
Record the range of data that MySQL update will lock
堆 AcWing 838. 堆排序
浏览器存储方案
Embedded Software Engineer career planning
Async/await asynchronous function
ASP. Net MVC default configuration, if any, jumps to the corresponding program in the specified area
JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
Typora+docsify quick start
Redis bloom filter