Created
February 24, 2019 00:22
-
-
Save xmlking/98a435076a612d8956c74fa57a73912c to your computer and use it in GitHub Desktop.
async generator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-ignore | |
const fetch = require('node-fetch'); | |
function delay(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
async function* getBooksPaged({ q, pageSize, lastPageIndex }) { | |
let currentIndex = 0; | |
let isDone = false; | |
while (currentIndex < lastPageIndex && !isDone) { | |
const pageResults = await getBooksPage({ | |
q, | |
startIndex: currentIndex, | |
maxResults: pageSize, | |
}); | |
yield pageResults; | |
if (pageResults.length < pageSize) { | |
isDone = true; | |
} else { | |
currentIndex++; | |
} | |
} | |
} | |
async function getBooksPage({ q, startIndex, maxResults }) { | |
const params = new URLSearchParams({ q, startIndex, maxResults }); | |
const response = await fetch(`https://www.googleapis.com/books/v1/volumes?${params.toString()}`); | |
const jsonResponse = await response.json(); | |
const mapEssentialInfo = ({ volumeInfo }) => ({ title: volumeInfo.title }); | |
if(jsonResponse && jsonResponse.items) { | |
return jsonResponse.items.map(mapEssentialInfo); | |
} else { | |
throw new Error('no items') | |
} | |
} | |
(async () => { | |
const pages = getBooksPaged({ q: 'bitcoin', pageSize: 3, lastPageIndex: 5 }); | |
console.log('1') | |
console.log('Searching books about bitcoin...'); | |
for await (const page of pages) { | |
console.log('Page Results : '); | |
console.log(page); // e.g. [ { title: 'Bitcoin: Introducción simple' }, { title: 'Bitcoin' }, { title: 'Bitcoins' } ] | |
await delay(1000); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment