簡體   English   中英

在nodejs中使用axios發送多個get請求

[英]Send multiple get requests with axios in nodejs

最初我需要發送一千多個請求。 但這將失敗而不會在請求之間暫停。 由於我是 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');
    }));

我試圖整合一個卧鋪。 但它只是沒有用。 它沒有在請求之間暫停

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM