Search code examples
node.jstypescriptgenerator

NodeJS: make less requests by API


I am trying to process response data and do not make next request before current data didn't processed. I tried use async/await and generators.

Generator:

    private *readData() {
        const currentUrl = this.getUrl();
        const requestSettings = this.getRequestSettings();
        yield axios.get( currentUrl, requestSettings).then( (response: any) => {
            console.log('Make request');
            return this.getData(response);
        });
    }

    *readItem() {
        let responseData: any;

        if (!responseData) {
            const response = this.readData();
            responseData = response.next();
        }
        console.log('res data:', responseData['value']);
        yield responseData['value'].then((res: any) => {
            return res;
        });
     }

and then in the main code I do next:

for (let i=0;i<10;i++) {
    item = transport.readItem().next();
    console.log("R:", item);
}

Another idea was using async/await


async readItems() {
    const headers = this.settings.headers;
    const response = await axios.get( url, {
        headers: headers
    });
    return response.data;
}

But in this case I get a promise in the response, if I just try to call this method 10 times.

I read 10 items, but I still make 10 requests to the server. Is it possible make one request, processed 10 items, and then make the second request? Maybe I have to use another pattern or whatever.


Solution

  • I found next solution

    (async () => {
        for (let i = 0; i < 10; i++) {
            item = await transport.readItem();
            console.log("R:", item);
        }
    })();
    

    because I ran this part of code inside script without any functions/methods