⏪ Вернуться в оглавление

About the author


Author: https://t.me/ahillary

Resources


Channel: https://t.me/semolina_code_python

Chat: https://t.me/python_with_ahillary

YouTube: https://www.youtube.com/@semolinacode

Coding training: https://t.me/how_to_code_web3

Prop trading: https://t.me/semolina_prop


Содержание

Асинхронные итераторы и генераторы

Синхронный итератор

«Обычный» перебираемый объект, как подробно рассказано в главе Перебираемые объекты, выглядит примерно так:

const myIterable = {
	from: 10,
	to: 15,
  
	[Symbol.iterator](): Iterator<number> {
		let current = this.from;
  	const end = this.to;
  
  	return {
			next(): IteratorResult<number> {
				if (current <= end) {
					return { value: current++, done: false };
				} else {
					return { value: undefined, done: true };
				}
			}
  	};
	}
};
  
const numbers = Array.from(myIterable);
console.log(numbers); // [ 10, 11, 12, 13, 14, 15 ]

Асинхронный итератор

Асинхронные итераторы позволяют перебирать данные, поступающие асинхронно. Например, когда мы загружаем что-то по частям по сети. Асинхронные генераторы делают такой перебор ещё удобнее.