在 nodejs 中使用 axios 发送多个 get 请求

时间:2021-05-17 10:16:45

标签: node.js 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,
                    lastname: p.lastName,
                    organisation: p.organisation,
                    thirdPartyId: p.id,
                    prefix: p.degree
                }
                speakers.push(speaker);
            }
            newParticipants.push(participant);

            //await new Promise(r => setTimeout(r, 1000));
        }
        console.log('q');
    }));

我尝试集成一个卧铺。但它只是没有用。请求之间没有暂停

1 个答案:

答案 0 :(得分:1)

当您使用 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 秒的“睡眠”。