tzkmx
4/21/2020 - 1:14 AM

Learning to use iterable of fetch Promises

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))
    })
}