当前位置:网站首页>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()
边栏推荐
- Record the range of data that MySQL update will lock
- bellman-ford AcWing 853. Shortest path with side limit
- Deep copy event bus
- 哈希表 AcWing 840. 模拟散列表
- spfa AcWing 851. spfa求最短路
- Hash table acwing 841 String hash
- Drools terminates the execution of other rules after executing one rule
- Deep Copy Event bus
- Linear DP acwing 898 Number triangle
- Use MySQL events to regularly perform post seven world line tasks
猜你喜欢
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
spfa AcWing 852. spfa判断负环
Modular commonjs es module
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph
Linear DP acwing 897 Longest common subsequence
JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
随机推荐
Shutter encapsulated button
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
Async/await asynchronous function
. Net wechat message template push
上手报告|今天聊聊腾讯目前在用的微服务架构
[ybtoj advanced training guidance] cross the river [BFS]
堆 AcWing 839. 模拟堆
线性DP AcWing 898. 数字三角形
Modular commonjs es module
Use sqoop to export ads layer data to MySQL
Linear DP acwing 896 Longest ascending subsequence II
模块化 CommonJS ES Module
Drools dynamically add, modify, and delete rules
Execute any method of any class through reflection
FBX import under ue4/ue5 runtime
软件测试面试题-2022年大厂面试题合集
Redis avalanche, penetration, breakdown
What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
Some sudden program ideas (modular processing)
JSON serialization and parsing