[Fixed] Implementing Recursive Function with Async and Await with Angular 10

Issue

I am trying to fetch a set of images as base64. To utilize max bandwidth, we planned to fetch one image after the other.

Below is the code

const input = ['url1']; //Array of image urls

this.recursiveFunction(input, 0, []).then((res: any) => {
    console.log(res);
});

async recursiveFunction(urls: any, index = 0, responses: any = []){
    const url = urls[index];
    return await this.srv.getData({ url: url }).subscribe((response: any) => {
        responses.push(response);
        if (responses.length !== urls.length) {
            return this.recursiveFunction(urls, index + 1, responses);
        }
        return responses;
    });

}

Tested with 6 images, the service calls are working fine.

But i see the console.log(res) outputs immediately the function is called (before the first service call) and is shown as below

enter image description here

The responses are having all 6 images base64 data. How to fetch the responses at the end of the last service call

Solution

Change your method to :-

async recursiveFunction(urls: any){
    const url = urls[index];
    return await getImages(urls);
}



async getImages(urls: any) {
       const responses = [];
       for(const url of urls) {
        const res = await this.srv.getData({ url: url }).toPromise();
        responses.push(res);
       }
       return responses;
   }

now you can just pass array of urls and you will get images in response.

Leave a Reply

(*) Required, Your email will not be published