简体   繁体   中英

How to efficiently make multiple api calls from an array in node js

I have the following snippet of code to make multiple api calls

var userdetails:any=[]
for(var i=0;i<userids.length;i++)
            {
                               userdetails.push(await this.getUserData(authToken,userid[i]))
            }

Implementation of getUserData function is as follows

async getUserData(authtoken,userid) {
        return new Promise((resolve, reject) => {
        
            const url = `https://***********/***/users?id=userid`;
            const requestOptions = {
                url,
                method: 'GET',
                headers: {
                    'Authorization': authtoken,
                }
            };
            request(requestOptions, (err, response, body) => {
                let errorMessage = 'Error in getting data';
                if (err) {
                    
                    return reject(err);
                }

                if (!response) {
                    
                    return reject({
                        message: errorMessage
                    });
                }

                if (response.statusCode === 200) {
                    
                    try {
                        body = JSON.parse(body);
                    } catch (err) {
                        
                        reject({ message: errorMessage });
                    }
                    if (isArray(body)) {
                        let newArray: any = [];
                        body.forEach(element => {
                            newArray.push({         
                                userId:element["userId"],
                                username:element["username"],
                                
                            });
                        });
                        return resolve(newArray);
                    } else {
                        return resolve(body);
                    }
                }

                if (response.statusCode >= 400) {
                    return reject({
                        message: errorMessage
                    });
                }
            });
        });
    }

The above code works just fine and returns all the data. But there is a performance glitch in it and it is taking lot of time to return the data as the number of userid's increase. I am already using async await approach. How else can I implement it to tune the performance of this code?

You should use Promise.all() or Promise.allSettled() instead of awaiting them one by one. It should make the program much faster.

Example:

const requests = [];

for (let i = 0; i < userids.length; i++) {
    requests.push(this.getUserData(authToken, userid[i]));
}

const userdetails = await Promise.all(requests);

And try to use some libraries that have build-in promise support. They will make your code much simpler and cleaner. I can recommend using axios and node-fetch . They both support promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM