簡體   English   中英

等待 api 響應處理完再迭代 for 循環

[英]Wait for api response to be processed before iterating for loop

我正在嘗試編寫一個 Discord 機器人,它基本上使用 HTTP 請求檢查每個 Discord 用戶是否在會員數據庫中具有有效會員資格(尚未過期)所以我寫了如下內容

function checkmemberships() {

    const memberships = fs.readFileSync('emailtest.txt').toString().toLowerCase().replace(/(?:\\[rn]|[\r\n]+)+/g, " ").split(" ");

    const tenantId = 'example';
    var today = new Date().toISOString().slice(0, 10);

    for (i = 0; i < memberships.length; i += 3)
    {

        let contactId = memberships[i];
        const membershipnumber = memberships[i + 1];
        fetch(`https://rolodex.api.rhythmsoftware.com/contacts/${tenantId}/number/${contactId}`,
                {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': global.apikey //this is generated somewhere else
                    },
                }
        )
                .then((res) => res.json())
                .then((res) => {
                    if (res.errorMessage == "RecordNotFound: Could not find a contact with the supplied number")
                    {
                        //Still To Do but not important
                    } else
                    {
                        if (res.id)
                        {
                            contactId = res.id; //Number can actually be different from what the user originally posts
                            fetch(`https://membership.api.rhythmsoftware.com/memberships/${tenantId}/contact/${contactId}`,
                                    {
                                        method: 'GET',
                                        headers: {
                                            'Content-Type': 'application/json',
                                            'Authorization': global.apikey
                                        },
                                    }
                            )
                                    .then((resp) => resp.json())
                                    .then((resp) => {
                                        console.log(resp);
                                        if (resp.expiration_date)
                                        {
                                            let guild = client.guilds.cache.get('890266470641201172');
                                            let member = guild.members.cache.get(membershipnumber); //At this point the membership isn't found because at this point it's undefined
                                            if (resp.expiration_date <= today) {
                                                member.roles.remove("890270511261696031");
                                                member.roles.remove("890270660239175700");
                                            }

                                        }
                                    })
                        }
                    }
                })
    }
}

這在檢查一個成員資格時有效,但是當我開始引入其他成員資格時,我注意到 for 循環在我什至還沒有得到第一個成員資格的響應之前就已經完成,此時不再定義成員資格。

我怎樣才能更改上面的代碼,以便 for 循環在執行下一次迭代之前等待 HTTP 響應被處理?

我會使用await fetch()來確保 API 響應已完成,然后您才能對數據執行任何操作。 這將阻止您在響應完成之前處理數據。

因此,在您的情況下,您應該更改您的代碼,以便您的 await fetch 首先在循環之外完成,這與您現在的方式相反。 這是一篇關於如何使用 Await Fetch 的非常好的文章。

https://dmitripavlutin.com/javascript-fetch-async-await/#2-fetching-json

在循環中等待將按順序進行檢查。 如果它們不相互依賴,則與 Promise.all 同時運行檢查。

function checkmemberships() {
    const memberships = fs.readFileSync('emailtest.txt').toString().toLowerCase().replace(/(?:\\[rn]|[\r\n]+)+/g, " ").split(" ");

    const tenantId = 'example';
    var today = new Date().toISOString().slice(0, 10);

    let promises = [];
    for (i = 0; i < memberships.length; i += 3) {
        let contactId = memberships[i];
        const membershipnumber = memberships[i + 1];
        promises.push(checkMembership(tenentId, membershipnumber, today);
    }
    return Promise.all(promises);
}


function checkMembership(tenentId, membershipnumber, today) {
  // .... from the op
  return fetch(`https://rolodex.api.rhythmsoftware.com/contacts/${tenantId}/number/${contactId}`, // ...
    // .then do json parse
    // .then do expiration check
      // return something, like a bool if the member is in good standing
}

暫無
暫無

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

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