Slide 1

Slide 1 text

Finding a lost song with Node.js & async iterators Luciano Mammino ( ) @loige 2021-10-18 loige.link/nodeconf-iter 1

Slide 2

Slide 2 text

Get these slides! loige loige.link/nodeconf-iter 2

Slide 3

Slide 3 text

Photo by on Darius Bashar Unsplash A random song you haven't listened to in years pops into your head... πŸ‘‚πŸ› 3

Slide 4

Slide 4 text

It doesn't matter what you do all day... It keeps coming back to you! πŸ› Photo by on Attentie Attentie Unsplash 4

Slide 5

Slide 5 text

And now you want to listen to it! Photo by on Volodymyr Hryshchenko Unsplash 5

Slide 6

Slide 6 text

But, what if you can't remember the title or the author?! Photo by on Tachina Lee Unsplash 6

Slide 7

Slide 7 text

THERE MUST BE A WAY TO REMEMBER! Photo by on Marius Niveri Unsplash 7

Slide 8

Slide 8 text

Today, I'll tell you how I solved this problem using - Last.fm API - Node.js - Async Iterators Photo by on Quinton Coetzee Unsplash 8

Slide 9

Slide 9 text

Let me introduce myself first... 9

Slide 10

Slide 10 text

Let me introduce myself first... πŸ‘‹ I'm Luciano ( πŸ•πŸ) 9

Slide 11

Slide 11 text

Let me introduce myself first... πŸ‘‹ I'm Luciano ( πŸ•πŸ) Senior Architect @ fourTheorem (Dublin ) 9

Slide 12

Slide 12 text

Let me introduce myself first... πŸ‘‹ I'm Luciano ( πŸ•πŸ) Senior Architect @ fourTheorem (Dublin ) nodejsdp.link πŸ“” Co-Author of Node.js Design Patterns πŸ‘‰ 9

Slide 13

Slide 13 text

Let me introduce myself first... πŸ‘‹ I'm Luciano ( πŸ•πŸ) Senior Architect @ fourTheorem (Dublin ) nodejsdp.link πŸ“” Co-Author of Node.js Design Patterns πŸ‘‰ Let's connect! (blog) (twitter) (twitch) (github) loige.co @loige loige lmammino 9

Slide 14

Slide 14 text

We are business focused technologists that deliver. | | Accelerated Serverless AI as a Service Platform Modernisation We are hiring: do you want to ? work with us loige 10

Slide 15

Slide 15 text

So, there was this song in my mind... πŸ› loige 11

Slide 16

Slide 16 text

I could only remember some random parts and the word "dark" (probably in the title) loige 12

Slide 17

Slide 17 text

13

Slide 18

Slide 18 text

14

Slide 19

Slide 19 text

loige 15

Slide 20

Slide 20 text

Luciano - scrobbling since 12 Feb 2007 loige 15

Slide 21

Slide 21 text

Luciano - scrobbling since 12 Feb 2007 loige ~250k scrobbles... that song must be there! 15

Slide 22

Slide 22 text

loige There's an API! https://www.last.fm/api 16

Slide 23

Slide 23 text

loige 17

Slide 24

Slide 24 text

loige Let's give it a shot curl "http://ws.audioscrobbler.com/2.0/? method=user.getrecenttracks&user=loige&api_key =${API_KEY}&format=json" | jq . 18

Slide 25

Slide 25 text

loige 19

Slide 26

Slide 26 text

It works! πŸ₯³ Now let's do this with JavaScript loige 20

Slide 27

Slide 27 text

import { request } from 'undici' const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json' }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) loige 21

Slide 28

Slide 28 text

import { request } from 'undici' const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json' }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) loige 21

Slide 29

Slide 29 text

import { request } from 'undici' const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json' }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) loige 21

Slide 30

Slide 30 text

import { request } from 'undici' const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json' }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) loige 21

Slide 31

Slide 31 text

import { request } from 'undici' const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json' }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) loige 21

Slide 32

Slide 32 text

loige 22

Slide 33

Slide 33 text

loige We are getting a "paginated" response with 50 tracks per page 22

Slide 34

Slide 34 text

loige We are getting a "paginated" response with 50 tracks per page but there are 51 here! πŸ€” 22

Slide 35

Slide 35 text

loige We are getting a "paginated" response with 50 tracks per page but there are 51 here! πŸ€” (let's ignore this for now...) 22

Slide 36

Slide 36 text

loige We are getting a "paginated" response with 50 tracks per page but there are 51 here! πŸ€” How do we fetch the next pages? (let's ignore this for now...) 22

Slide 37

Slide 37 text

loige 23

Slide 38

Slide 38 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 39

Slide 39 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 40

Slide 40 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 41

Slide 41 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 42

Slide 42 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 43

Slide 43 text

let page = 1 while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', page }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() console.log(data) if (page === Number(data.recenttracks['@attr'].totalPages)) { break // it's the last page! } loige 24

Slide 44

Slide 44 text

loige 25

Slide 45

Slide 45 text

loige 25

Slide 46

Slide 46 text

Seems good! πŸ‘Œ Let's look at the tracks... loige 26

Slide 47

Slide 47 text

// ... for (const track of data.recenttracks.track) { console.log( track.date?.['#text'], `${track.artist['#text']} - ${track.name}` ) } console.log('--- end page ---') // ... loige 27

Slide 48

Slide 48 text

loige 28

Slide 49

Slide 49 text

loige * Note that page size here is 10 tracks per page 28

Slide 50

Slide 50 text

loige * Note that page size here is 10 tracks per page Every page has a song with undefined time... This is the song I am currently listening to! It appears at the top of every page. 28

Slide 51

Slide 51 text

loige * Note that page size here is 10 tracks per page Sometimes there are duplicated tracks between pages... 😨 28

Slide 52

Slide 52 text

The "sliding windows" problem 😩 loige 29

Slide 53

Slide 53 text

loige ... tracks (newest to oldest) 30

Slide 54

Slide 54 text

loige ... tracks (newest to oldest) 30 Page1 Page2

Slide 55

Slide 55 text

loige ... tracks (newest to oldest) 30 Page1 Page2 ...

Slide 56

Slide 56 text

loige ... tracks (newest to oldest) 30 Page1 Page2 ... new track

Slide 57

Slide 57 text

loige ... tracks (newest to oldest) 30 Page1 Page2 ... Page1 Page2 new track

Slide 58

Slide 58 text

loige ... tracks (newest to oldest) 30 Page1 Page2 ... Page1 Page2 new track moved from page 1 to page 2

Slide 59

Slide 59 text

loige 31

Slide 60

Slide 60 text

Time based windows 😎 loige 32

Slide 61

Slide 61 text

loige ...* tracks (newest to oldest) 33 * we are done when we get an empty page (or num pages is 1) to ... from

Slide 62

Slide 62 text

loige ...* tracks (newest to oldest) 33 Page1 * we are done when we get an empty page (or num pages is 1) to ... from

Slide 63

Slide 63 text

loige ...* tracks (newest to oldest) 33 Page1 t1 * we are done when we get an empty page (or num pages is 1) to ... from

Slide 64

Slide 64 text

loige ...* tracks (newest to oldest) 33 Page1 before t1 (page 1 "to" t1) t1 * we are done when we get an empty page (or num pages is 1) to ... from

Slide 65

Slide 65 text

loige ...* tracks (newest to oldest) 33 Page1 before t1 (page 1 "to" t1) t1 t2 * we are done when we get an empty page (or num pages is 1) to ... from

Slide 66

Slide 66 text

loige ...* tracks (newest to oldest) 33 Page1 before t1 (page 1 "to" t1) t1 t2 before t2 (page 1 "to" t2) * we are done when we get an empty page (or num pages is 1) to ... from

Slide 67

Slide 67 text

let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', limit: '10', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track console.log( `--- ↓ page to ${to}`, `remaining pages: ${data.recenttracks['@attr'].totalPages} ---` ) for (const track of tracks) { console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`) } if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } loige 34

Slide 68

Slide 68 text

let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', limit: '10', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track console.log( `--- ↓ page to ${to}`, `remaining pages: ${data.recenttracks['@attr'].totalPages} ---` ) for (const track of tracks) { console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`) } if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } loige 34

Slide 69

Slide 69 text

let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', limit: '10', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track console.log( `--- ↓ page to ${to}`, `remaining pages: ${data.recenttracks['@attr'].totalPages} ---` ) for (const track of tracks) { console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`) } if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } loige 34

Slide 70

Slide 70 text

let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', limit: '10', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track console.log( `--- ↓ page to ${to}`, `remaining pages: ${data.recenttracks['@attr'].totalPages} ---` ) for (const track of tracks) { console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`) } if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } loige 34

Slide 71

Slide 71 text

let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user: 'loige', api_key: process.env.API_KEY, format: 'json', limit: '10', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track console.log( `--- ↓ page to ${to}`, `remaining pages: ${data.recenttracks['@attr'].totalPages} ---` ) for (const track of tracks) { console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`) } if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } loige 34

Slide 72

Slide 72 text

loige 35

Slide 73

Slide 73 text

loige The track of the last timestamp becomes the boundary for the next page 35

Slide 74

Slide 74 text

We have a working solution! πŸŽ‰ Can we generalise it? loige 36

Slide 75

Slide 75 text

We know how to iterate over every page/track. How do we expose this information? loige const reader = LastFmRecentTracks({ apikey: process.env.API_KEY, user: 'loige' }) 37

Slide 76

Slide 76 text

// callbacks reader.readPages( (page) => { /* ... */ }, // on page (err) => { /* ... */} // on completion (or error) ) loige 38

Slide 77

Slide 77 text

// event emitter reader.read() reader.on('page', (page) => { /* ... */ }) reader.on('completed', (err) => { /* ... */ }) loige 39

Slide 78

Slide 78 text

// streams ❀ reader.pipe(/* transform or writable stream here */) reader.on('end', () => { /* ... */ }) reader.on('error', () => { /* ... */ }) loige 40

Slide 79

Slide 79 text

// streams pipeline ❀ ❀ pipeline( reader, yourProcessingStream, (err) => { // handle completion or err } ) loige 41

Slide 80

Slide 80 text

// ASYNC ITERATORS! 😡 for await (const page of reader) { /* ... */ } // ... do more stuff when all the // data is consumed loige 42

Slide 81

Slide 81 text

// ASYNC ITERATORS WITH ERROR HANDLING! 🀯 try { for await (const page of reader) { /* ... */ } } catch (err) { // handle errors } // ... do more stuff when all the // data is consumed loige 43

Slide 82

Slide 82 text

How can we build an async iterator? 🧐 loige 44

Slide 83

Slide 83 text

Meet the iteration protocols! loige loige.co/javascript-iterator-patterns 45

Slide 84

Slide 84 text

Iteration concepts loige Iterator An object that acts as a cursor to iterate over blocks of data sequentially Iterable An object that contains data that can be iterated over sequentially ... ... 46

Slide 85

Slide 85 text

The iterator protocol An object is an iterator if it has a next() method. Every time you call it, it returns an object with the keys done (boolean) and value. loige 47

Slide 86

Slide 86 text

function createCountdown (from) { let nextVal = from return { next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 48

Slide 87

Slide 87 text

function createCountdown (from) { let nextVal = from return { next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 48

Slide 88

Slide 88 text

function createCountdown (from) { let nextVal = from return { next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 48

Slide 89

Slide 89 text

function createCountdown (from) { let nextVal = from return { next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 48

Slide 90

Slide 90 text

function createCountdown (from) { let nextVal = from return { next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 48

Slide 91

Slide 91 text

const countdown = createCountdown(3) console.log(countdown.next()) // { done: false, value: 3 } console.log(countdown.next()) // { done: false, value: 2 } console.log(countdown.next()) // { done: false, value: 1 } console.log(countdown.next()) // { done: false, value: 0 } console.log(countdown.next()) // { done: true } loige 49

Slide 92

Slide 92 text

Generator functions "produce" iterators! loige 50

Slide 93

Slide 93 text

function * createCountdown (from) { for (let i = from; i >= 0; i--) { yield i } } loige 51

Slide 94

Slide 94 text

function * createCountdown (from) { for (let i = from; i >= 0; i--) { yield i } } loige 51

Slide 95

Slide 95 text

function * createCountdown (from) { for (let i = from; i >= 0; i--) { yield i } } loige 51

Slide 96

Slide 96 text

const countdown = createCountdown(3) console.log(countdown.next()) // { done: false, value: 3 } console.log(countdown.next()) // { done: false, value: 2 } console.log(countdown.next()) // { done: false, value: 1 } console.log(countdown.next()) // { done: false, value: 0 } console.log(countdown.next()) // { done: true, value: undefined } loige 52

Slide 97

Slide 97 text

The iterable protocol An object is iterable if it implements the Symbol.iterator method, a zero-argument function that returns an iterator. loige 53

Slide 98

Slide 98 text

function createCountdown (from) { let nextVal = from return { [Symbol.iterator]: () => ({ next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } }) } } loige 54

Slide 99

Slide 99 text

function createCountdown (from) { let nextVal = from return { [Symbol.iterator]: () => ({ next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } }) } } loige 54

Slide 100

Slide 100 text

function createCountdown (from) { let nextVal = from return { [Symbol.iterator]: () => ({ next () { if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } }) } } loige 54

Slide 101

Slide 101 text

function createCountdown (from) { return { [Symbol.iterator]: function * () { for (let i = from; i >= 0; i--) { yield i } } } } loige 55

Slide 102

Slide 102 text

const countdown = createCountdown(3) for (const value of countdown) { console.log(value) } // 3 // 2 // 1 // 0 loige 56

Slide 103

Slide 103 text

OK. So far this is all synchronous iteration. What about async? πŸ™„ loige 57

Slide 104

Slide 104 text

The async iterator protocol An object is an async iterator if it has a next() method. Every time you call it, it returns a promise that resolves to an object with the keys done (boolean) and value. loige 58

Slide 105

Slide 105 text

import { setTimeout } from 'timers/promises' function createAsyncCountdown (from, delay = 1000) { let nextVal = from return { async next () { await setTimeout(delay) if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 59

Slide 106

Slide 106 text

import { setTimeout } from 'timers/promises' function createAsyncCountdown (from, delay = 1000) { let nextVal = from return { async next () { await setTimeout(delay) if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 59

Slide 107

Slide 107 text

import { setTimeout } from 'timers/promises' function createAsyncCountdown (from, delay = 1000) { let nextVal = from return { async next () { await setTimeout(delay) if (nextVal < 0) { return { done: true } } return { done: false, value: nextVal-- } } } } loige 59

Slide 108

Slide 108 text

const countdown = createAsyncCountdown(3) console.log(await countdown.next()) // { done: false, value: 3 } console.log(await countdown.next()) // { done: false, value: 2 } console.log(await countdown.next()) // { done: false, value: 1 } console.log(await countdown.next()) // { done: false, value: 0 } console.log(await countdown.next()) // { done: true } loige 60

Slide 109

Slide 109 text

const countdown = createAsyncCountdown(3) console.log(await countdown.next()) // { done: false, value: 3 } console.log(await countdown.next()) // { done: false, value: 2 } console.log(await countdown.next()) // { done: false, value: 1 } console.log(await countdown.next()) // { done: false, value: 0 } console.log(await countdown.next()) // { done: true } loige 60

Slide 110

Slide 110 text

loige 61

Slide 111

Slide 111 text

import { setTimeout } from 'timers/promises' // async generators "produce" async iterators! async function * createAsyncCountdown (from, delay = 1000) { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } loige 62

Slide 112

Slide 112 text

import { setTimeout } from 'timers/promises' // async generators "produce" async iterators! async function * createAsyncCountdown (from, delay = 1000) { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } loige 62

Slide 113

Slide 113 text

import { setTimeout } from 'timers/promises' // async generators "produce" async iterators! async function * createAsyncCountdown (from, delay = 1000) { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } loige 62

Slide 114

Slide 114 text

The async iterable protocol An object is an async iterable if it implements the Symbol.asyncIterator method, a zero- argument function that returns an async iterator. loige 63

Slide 115

Slide 115 text

import { setTimeout } from 'timers/promises' function createAsyncCountdown (from, delay = 1000) { return { [Symbol.asyncIterator]: async function * () { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } } } loige 64

Slide 116

Slide 116 text

import { setTimeout } from 'timers/promises' function createAsyncCountdown (from, delay = 1000) { return { [Symbol.asyncIterator]: async function * () { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } } } loige 64

Slide 117

Slide 117 text

HOT TIP πŸ”₯ With async generators we can create objects that are both async iterators and async iterables! loige (We don't need to specify Symbol.asyncIterator explicitly!) 65

Slide 118

Slide 118 text

import { setTimeout } from 'timers/promises' // async generators "produce" async iterators // (and iterables!) async function * createAsyncCountdown (from, delay = 1000) { for (let i = from; i >= 0; i--) { await setTimeout(delay) yield i } } loige 66

Slide 119

Slide 119 text

const countdown = createAsyncCountdown(3) for await (const value of countdown) { console.log(value) } loige 67

Slide 120

Slide 120 text

const countdown = createAsyncCountdown(3) for await (const value of countdown) { console.log(value) } loige 67

Slide 121

Slide 121 text

Now we know how to make our LastFmRecentTracks an Async Iterable 🀩 loige 68

Slide 122

Slide 122 text

import { request } from 'undici' async function* createLastFmRecentTracks (apiKey, user) { let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user, api_key: apiKey, format: 'json', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track yield tracks if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } } loige 69

Slide 123

Slide 123 text

import { request } from 'undici' async function* createLastFmRecentTracks (apiKey, user) { let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user, api_key: apiKey, format: 'json', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track yield tracks if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } } loige 69

Slide 124

Slide 124 text

import { request } from 'undici' async function* createLastFmRecentTracks (apiKey, user) { let to = '' while (true) { const query = new URLSearchParams({ method: 'user.getrecenttracks', user, api_key: apiKey, format: 'json', to }) const url = `https://ws.audioscrobbler.com/2.0/?${query}` const { body } = await request(url) const data = await body.json() const tracks = data.recenttracks.track yield tracks if (data.recenttracks['@attr'].totalPages <= 1) { break // it's the last page! } const lastTrackInPage = tracks[tracks.length - 1] to = lastTrackInPage.date.uts } } loige 69

Slide 125

Slide 125 text

const recentTracks = createLastFmRecentTracks( process.env.API_KEY, 'loige' ) for await (const page of recentTracks) { console.log(page) } loige 70

Slide 126

Slide 126 text

Let's search for all the songs that contain the word "dark" in their title! 🧐 loige 71

Slide 127

Slide 127 text

const recentTracks = createLastFmRecentTracks( process.env.API_KEY, 'loige' ) for await (const page of recentTracks) { for (const track of page) { if (track.name.toLowerCase().includes('dark')) { console.log(`${track.artist['#text']} - ${track.name}`) } } } loige 72

Slide 128

Slide 128 text

loige 73

Slide 129

Slide 129 text

loige OMG! This is the song! 😱 ...from 8 years ago! 73

Slide 130

Slide 130 text

For a more serious package that allows you to fetch data from Last.fm: loige npm install scrobbles 74

Slide 131

Slide 131 text

Cover Picture by on ❀ Thanks to Jacek Spera, , , , , for reviews and suggestions. FPVmat A Unsplash @eoins @pelger @gbinside @ManuEomm @simonplend - loige.link/nodeconf-iter loige.link/async-it-code for await (const _ of createAsyncCountdown(1_000_000)) { console.log("THANK YOU! 😍 ") } loige nodejsdp.link 75