在迭代循环之前,请等待api响应得到处理



我正在尝试编写一个Discord机器人程序,它基本上使用HTTP请求来检查每个Discord用户在成员数据库中是否有有效的成员资格(尚未过期(,所以我编写了如下

function checkmemberships() {
const memberships = fs.readFileSync('emailtest.txt').toString().toLowerCase().replace(/(?:\[rn]|[rn]+)+/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循环在我得到第一个成员身份的响应之前就已经完成了,此时不再定义membershipnumber。

我如何更改上面的代码,以便for循环在进行下一次迭代之前等待HTTP响应的处理?

我将使用await fetch()来确保API响应已完成,然后才能对数据执行任何操作。这将阻止您在响应完成之前处理数据。

因此,在您的情况下,您应该更改代码,使等待获取首先在循环之外完成,这与现在的情况相反。这里有一篇关于如何使用Await Fetch的非常好的文章。

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

循环中的Await将按顺序进行检查。如果它们不相互依赖,请与Promise.all.同时运行检查

function checkmemberships() {
const memberships = fs.readFileSync('emailtest.txt').toString().toLowerCase().replace(/(?:\[rn]|[rn]+)+/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
}

最新更新