Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ES2018 AsyncIteratorでキメる

ES2018 AsyncIteratorでキメる

EcmascriptのAsyncIteratorがどのように動くのか、iterator/generator/async・awaitの解説

More Decks by Taketoshi Aono(青野健利 a.k.a brn)

Other Decks in Programming

Transcript

  1. せ⵸: @brn (ꫬꅿ⨳ⵃa.k.a ـٕ٦ظ) 耵噟: ؿٗٝزؒٝسؒٝآص،٥iOSؒٝآص، ⠓爡: Cyberagent ،سذؙأةآؔRightSegment٥AI Messenger

    ـؚٗ: http://abcdef.gets.b6n.ch/ Twitter: https://twitter.com/brn227 GitHub: https://github.com/brn
  2. const arr = [1, 2, 3, 4, 5];! ! function

    iterator(arr) {! let currentIndex = 0;! const { length } = arr;! return {! next() {! return arr[currentIndex++];! },! done() {! return length =< currentIndex;! }! }! }! const iter = iterator(arr);! iter.next();! iter.next();!
  3. const arr = [1, 2, 3, 4, 5];! ! function

    generator(arr) {! const { length } = arr;! for (let i = 0; i < length; i++) {! yield arr[i];! }! }! const iter = generator(arr);! iter.next();! iter.next();!
  4. class MakanaiTechIterator {! *[Symbol.iterator]() {! yield "makanai";! yield "tech";! yield

    "teamspirit";! }! }! const mti = new MakanaiTechIterator();! for (const word of mti) {! console.log(word);! // makanai tech word! }! 
  5. async function timer(callback) {! return new Promise(resolve => {! setTimeout(()

    => resolve(callback()), 1000);! })! }! ! async function wait() {! const result = await timer(() => 'teamspirit!');! return result;! }! ! wait().then(v => console.log(v));!
  6. async function* asyncIterator() {! yield await fetch("/a");! yield await fetch("/b");!

    yield await fetch("/c");! }! const it = asyncIterator();! it.next().then(({value, done}) => {! console.log(value);! });! 
  7. async function* asyncIterator() {! yield await fetch("/a");! yield await fetch("/b");!

    yield await fetch("/c");! }! async function main() {! for await (const v of asyncIterator()) {! console.log(v) // Response object.! }! }!
  8. // Stream! const st = stream('http://ex.com/stream', {binary: true});! for await

    (const {chunk, ok, done} of st) {! console.log(chunk.read());! }!
  9. // DOM-Event! const a = document.querySelector('a');! for await (const {event,

    dispose} of event(a, 'click')) {! console.log(event.target.nodeName);! }!
  10. // Socket.IO! const URL = 'http://www.sample.com/ws';! for await (const {type,

    event} of ws(URL, io)) {! switch (type) {! case 'connection':! ...! case 'request':! ...! }! ...! }!