![](/img/trans.png)
[英]What's the best way to manage REST requests when each record requires multiple GET calls?
[英]What's the best way to send multiple requests to a server?
首先,我在 node.js 中使用模块 discord.js、request 和 request-promise 编写代码。 我无法向服务器发送大量(大约 70 个)不同的请求。 我不断从不同的请求中得到相同的结果。 'https://api.mojang.com/user/profiles/' + entry.uuid + '/names'
这就是我提出的请求,我有一个 forEach 循环遍历这样的 url 列表。 这是我的请求代码:
function getNames() {
count = 0;
msg.channel.send("Started getting Names");
urls.forEach(function() {
request(urls[count], function(err, res, body) {
if (!err && res.statusCode == 200) {
const obj = JSON.parse(body);
names[count] = body[0].name;
msg.channel.send(urls[count] + ", Username " + count + ": " + obj[0].name);
} else {
msg.channel.send("Username Error: " + err);
}
});
count++;
});
while (true) {
if (names.length != urls.length) {
msg.channel.send("Finished getting Names");
console.log("UUIDs:" + urls.join(", "));
console.log("Names:" + names.join(", "));
break;
}
}
}
我用于调试代码的msg.channel.send
命令(如果您好奇,可以使用 discord.js)。 现在,我的问题是: msg.channel.send(urls[count] + ", Username " + count + ": " + obj[0].name);
总是给我一个新的 url 但与第一个请求相同的用户名( obj[0].name
始终相同)。 所以,假设我有 3 个不同的 URL,第一个 URL 的用户名是 Evan,第二个是 Jack,第三个是 John。 当我运行代码时,我的名字数组将是["Evan", "Evan", "Evan"]
而不是["Evan", "Jack", "John"]
。 我认为这是因为我的代码在继续之前没有等待请求结果。 我相信可能有很多更好的方法可以做到这一点,我会很感激任何提示。
演示: https://repl.it/@kallefrombosnia/OldfashionedQuintessentialConditions
// request package is deprecated so I use this one
const fetch = require('node-fetch');
// random mojang acc's
const urls = [
'https://api.mojang.com/user/profiles/7125ba8b1c864508b92bb5c042ccfe2b/names',
'https://api.mojang.com/user/profiles/97f2453a361b44fa9312c496b67f24fc/names',
'https://api.mojang.com/user/profiles/ac224782efff4296b08cdbde8e47abdb/names',
];
getNames = () => {
let names = [];
let round = 0;
// parse trough urls
urls.forEach((url, index) => {
// fetch url info
fetch(url).then(res =>
// json convert
res.json())
.then(jsonBody => {
// iteration level
round++;
// add name to the array
names.push(jsonBody[0].name);
// print some info about user
console.log(urls[index] + ", Username " + index + ": " + jsonBody[0].name);
// if this is last round and number of names is same as urls number print all info about users
if (round === urls.length && names.length === urls.length) {
console.log("Finished getting Names");
console.log("UUIDs:" + urls.join(", "));
console.log("Names:" + names.join(", "));
}
})
})
}
getNames();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.