Last active
April 21, 2020 01:43
-
-
Save tzkmx/fab3eff5d82cc3cf2d48a4d7a5daa256 to your computer and use it in GitHub Desktop.
Learning to use iterable of fetch Promises
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
interface MiniRequest { | |
url: string | |
body?: any | |
} | |
async function runSeq(requests: MiniRequest[]) { | |
for await (const result of buildIterable(requests)) { | |
console.log(result) | |
} | |
} | |
async function runSeqGen(requests: MiniRequest[]) { | |
for await (const result of iterableGenerator(requests)) { | |
console.log(result) | |
} | |
} | |
function* iterableGenerator(requests: MiniRequest[]) { | |
let current = 0 | |
while (current < requests.length) { | |
yield runFetch(requests[current++].url) | |
} | |
} | |
function buildIterable<T> (requests: MiniRequest[]): Iterable<Promise<T>>{ | |
return { | |
[Symbol.iterator]() { | |
const length = requests.length | |
let current = 0 | |
return { | |
next() { | |
if (current < length) { | |
const promise = runFetch(requests[current].url) | |
current++ | |
return {done: false, value: promise} | |
} | |
return {done: true, value: undefined} | |
} | |
} | |
} | |
} | |
} | |
function runFetch(url: string) { | |
return fetch(url).then(res => res.json()) | |
} | |
const requests = [ | |
{url: 'https://jsonplaceholder.typicode.com/todos/1'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/2'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/3'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/4'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/5'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/6'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/7'}, | |
{url: 'https://jsonplaceholder.typicode.com/todos/8'}, | |
] | |
function runBomb(requests: MiniRequest[]): void { | |
requests.forEach(function ({url}, current) { | |
fetch(requests[current].url) | |
.then((response: Response) => response.json()) | |
.then(data => console.log(data)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment