forEach循环中的Javascript-API队列
目标摘要forEach循环中的Javascript-API队列,javascript,node.js,api,loops,queue,Javascript,Node.js,Api,Loops,Queue,目标摘要 async function refreshStats() { try { // get list of all fortnite users const fnUserList = await Users.find({}, "_id fnUserPlatform"); // my fnUser _id 5cca01ea8f52f40117b2ff51 fnUserList.forEach(async fnUser => { //make
async function refreshStats() {
try {
// get list of all fortnite users
const fnUserList = await Users.find({}, "_id fnUserPlatform"); // my fnUser _id 5cca01ea8f52f40117b2ff51
fnUserList.forEach(async fnUser => {
//make API call. apiCall is a function I created to make the API call and format the response
const { lifeStats, statsEqual } = await apiCall(
fnUser.fnUserPlatform
);
//execute other functions with apiCall response
});
} catch (err) {
console.error("error in refreshStats", err);
}
}
我需要在Node.js后端为API调用实现一个API队列。我需要遵守的API速率限制是每2秒1个请求,这是一个硬限制。我在forEach循环中进行API调用,因为我需要为每个用户执行一个API调用
我在网上找到了很多关于如何创建队列的文章,但它们大多涉及向数组添加API调用,因此我不确定在这种情况下如何实现队列
任何帮助都会非常感激,如果有帮助,我可以分享更多的代码
代码
async function refreshStats() {
try {
// get list of all fortnite users
const fnUserList = await Users.find({}, "_id fnUserPlatform"); // my fnUser _id 5cca01ea8f52f40117b2ff51
fnUserList.forEach(async fnUser => {
//make API call. apiCall is a function I created to make the API call and format the response
const { lifeStats, statsEqual } = await apiCall(
fnUser.fnUserPlatform
);
//execute other functions with apiCall response
});
} catch (err) {
console.error("error in refreshStats", err);
}
}
如果我没弄错的话。您可以利用
生成器功能
并将其与设置间隔
相结合。您可以创建一个队列函数,在指定的时间间隔内对其项进行排队
创建一个生成器函数基本上会生成一个apiCall并暂停
异步函数*queueGenerator(用户列表){
for(让用户列表的用户){
const result={lifeStats,statsqual}=wait apiCall(fnUser.fnuersplatform);
产量结果;
}
}
然后在您的方法中创建一个队列,并使用setInterval对项目进行排队
还有另一种方法是将setTimeout
与Promise
s结合使用。这涉及到创建承诺,以足够的延迟在setTimeOut中解决
异步函数refreshStatsV2(){
const fnUserList=await Users.find({},“_idfnuserplatform”);
const promises=fnUserList.map((fnUser,ix)=>(
新承诺(解决=>
setTimeout(异步()=>{
常数结果={
生命状态,
statsEqual
}=等待apiCall(ix.fnUserPlatform);
决心(结果);
},ix*2000)//每延迟下一项2秒
)));
const result=等待承诺。全部(承诺);//全部等待
控制台日志(结果);
}
如果我没弄错的话。您可以利用
生成器功能
并将其与设置间隔
相结合。您可以创建一个队列函数,在指定的时间间隔内对其项进行排队
创建一个生成器函数基本上会生成一个apiCall并暂停
异步函数*queueGenerator(用户列表){
for(让用户列表的用户){
const result={lifeStats,statsqual}=wait apiCall(fnUser.fnuersplatform);
产量结果;
}
}
然后在您的方法中创建一个队列,并使用setInterval对项目进行排队
还有另一种方法是将setTimeout
与Promise
s结合使用。这涉及到创建承诺,以足够的延迟在setTimeOut中解决
异步函数refreshStatsV2(){
const fnUserList=await Users.find({},“_idfnuserplatform”);
const promises=fnUserList.map((fnUser,ix)=>(
新承诺(解决=>
setTimeout(异步()=>{
常数结果={
生命状态,
statsEqual
}=等待apiCall(ix.fnUserPlatform);
决心(结果);
},ix*2000)//每延迟下一项2秒
)));
const result=等待承诺。全部(承诺);//全部等待
控制台日志(结果);
}
您可以使用from-package。您可以使用from-package。