[英]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我有以下代码片段可以进行多个 api 调用
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 getUserData function的实现如下
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.但是其中存在性能故障,并且随着用户ID数量的增加,返回数据需要花费大量时间。 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.您应该使用Promise.all()或Promise.allSettled()而不是一一等待它们。 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.并尝试使用一些内置 promise 支持的库。 They will make your code much simpler and cleaner.它们将使您的代码更简单、更清晰。 I can recommend using axios and node-fetch .我可以推荐使用axios和node-fetch 。 They both support promises.他们都支持承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.