簡體   English   中英

向服務器發送多個請求的最佳方式是什么?

[英]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.

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