如何解决在 nodejs 中使用 axios 发送多个 get 请求
最初我需要发送超过一千个请求。但这将失败而不会在请求之间暂停。因为我是 nodejs 的新手,所以我不知道如何处理这个.. 这是我当前的代码:
async getParticipantInfos(id) {
const url = 'https://..../'+id+'?..=..';
try {
const resp = await axios.get(url,{
headers: {
'Accept': 'application/json','Authorization': 'Bearer '+this.accesstoken
}
});
return setTimeout(() => resp.data.participant,1000);
} catch(err) {
console.log(err);
}
}
await Promise.all(participants.map(async (p) => {
// only imports participants with the state ID of 1 = Online!
if(p.participantStateId === 1) {
const participantInfos = await this.getParticipantInfos(p.id);
//console.log(participantInfos);
// make req to get more info about person
let participant = {
firstname: p.firstName,lastname: p.lastName,organisation: p.organisation,email: p.email,//code: participantInfos.vigenere2Code,participationType: p.participantTypeId,thirdPartyId: p.id,prefix: p.degree
}
// if participant === speaker then insert them into presentesr table as well
if(p.participantTypeId === 2) {
let speaker = {
id: p.id,firstname: p.firstName,prefix: p.degree
}
speakers.push(speaker);
}
newParticipants.push(participant);
//await new Promise(r => setTimeout(r,1000));
}
console.log('q');
}));
我尝试集成一个卧铺。但它只是没有用。请求之间没有暂停
解决方法
当您使用 Promise.all([...]) 时,所有请求将同时运行。
如果您希望它们按顺序发生,则需要执行以下操作:
async function allRequests(participants) {
const onlineParticipants = participant.filter(p => p.participantStateId === 1);
for (participant of onlineParticipants) {
const result = await getParticipantInfos(participant.id);
// rest of code here...
}
}
如果您想在请求之间“休眠”,可以执行以下操作:
async function allRequests(participants) {
const onlineParticipants = participant.filter(p => p.participantStateId === 1);
for (participant of onlineParticipants) {
const result = await getParticipantInfos(participant.id);
// rest of code here...
await new Promise((resolve) => setTimeout(() => resolve(),1000));
}
}
其中 1000 是 1 秒的“睡眠”。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。