簡體   English   中英

Node.js forEach進入數組

[英]Node.js forEach into array

我正在嘗試查詢以這種格式返回結果的主服務器:

[
    { ip: '127.0.0.1', port: 28961 },
    { ip: '127.0.0.1', port: 28965 }
]

然后,我需要用queryDedicated查詢每個服務器及其IP,然后在回調中返回數據(與queryMaster相同)。

如果回調中返回的數據有效,它將把它添加到一個數組中,最后將整個服務器數組打印到控制台。

var servers = {};

function blabla(host, port) {
    queryMaster(host, port, function(data) {
       async.forEach(data, function(key, next) {
            queryDedicated(key.ip, key.port, function(srv) {
                if (srv) {
                    // if callback data valid, add to array
                    servers[key.ip + ':' + key.port] = srv;
                }
            })

            // valid or not, continue
            next();
        }, function(err) {
            // print servers array
            console.log(servers);
        });
    });
}

問題是我的服務器陣列為空。

最終的“服務器”數組應以以下格式輸出數據:

{
    "176.57.141.60:28960": {
        "hostname": "board.landstuhl-atzel.de Schlachthaus #1",
        "address": "176.57.141.60:28960",
        "gametype": "war",
        "mapname": "mp_rundown",
        "players": "0",
        "max_players": "18"
    },
    "176.57.142.144:28663": {
        "hostname": "ClassicSnD.org No mercy for hackers. No lag. No bullshit. [B3]",
        "address": "176.57.142.144:28663",
        "gametype": "sd",
        "mapname": "mp_favela",
        "players": "0",
        "max_players": "18"
    }
}

謝謝!

注意:我假設您正在使用async模塊

async

雖然forEach函數可以工作,但我建議嘗試使用異步的reduce函數:

  function blabla(host, port) {
    queryMaster(host, port, function(data) {
       async.reduce(data, {}, function(memo, item, next){
          queryDedicated(item.ip, item.port, function(srv) {
            if (srv) {
              memo[item.ip+':'+item.port] = srv;
            }
            // valid or not, continue
            next(null, memo);
          });
     }, function(err, result) {
        // print servers array
        console.log(result);
      });
    });
  }

您可以將備注作為空對象傳遞,而不必使用全局servers對象:如果仍然需要全局對象,只需將servers變量作為備注傳遞。

香草JS的替代解決方案

// simple "parallel" async iterator
function asyncIterator(array, callback, lastCallback){
  var completed = 0;
  array.forEach(function(item){
    callback(item, end);
  });
  function end(){
    completed += 1;
    if(completed >= array.length){
      lastCallback();
    }
  }
}

var servers = {};

function blabla(host, port) {
  queryMaster(host, port, function(data) {
     asyncIterator(data, function(item, next){
       queryDedicated(item.ip, item.port, function(srv) {
          if (srv) {
            servers[item.ip+':'+item.port] = srv;
          }
          // valid or not, continue
          next();
        });
   }, function() {
      // print servers array
      console.log(servers);
    });
  });
}

請注意,這種原始解決方案非常簡單:迭代器不考慮輸入驗證或錯誤。 如果您打算使用許多async調用,我建議您使用上面的庫,這將使您的生活更輕松。

暫無
暫無

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

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