Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active April 21, 2020 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/fab3eff5d82cc3cf2d48a4d7a5daa256 to your computer and use it in GitHub Desktop.
Save tzkmx/fab3eff5d82cc3cf2d48a4d7a5daa256 to your computer and use it in GitHub Desktop.
Learning to use iterable of fetch Promises
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