【问题标题】:Can´t output correctly pushed content into array on node.js无法将内容正确输出到 node.js 上的数组中
【发布时间】:2018-03-16 11:33:22
【问题描述】:

)

我正在开发一个 node.js express 自定义 API 项目。 目前我在尝试推送数据时遇到问题......

这是我的代码:

module.exports = function(config, steamClient, csgo, database, teamspeakClient, router) {
var async = require('async'),
apicache = require('apicache'),
cache = apicache.middleware,
mysql = require('mysql');

async.waterfall([
    function(callback) {
        router.get('/CsgoUser/requestPlayersProfile/v1/:steamids', function(req, res) {
            var steamids = req.params.steamids.split(',');
            var csgo_data = [];
            steamClient.getPersonas(steamids, function(resp) {
                Object.keys(resp).forEach(function (steamid){
                    if (!steamClient.myFriends.hasOwnProperty(steamid)) {
                        if (resp[steamid].game_played_app_id == 730) {
                            csgo.requestPlayersProfile(steamid, function(result) {
                                console.log(result);
                                csgo_data.push(csgo_data, {steamid: steamid, response: result});

                            });
                        }else{
                            csgo_data.push({steamid: steamid, response: steamid + " is not playing csgo"});
                        }                   
                    }else{
                        csgo_data.push({steamid: steamid, response: steamid + " Is not bot´s friend..."});
                    }
                });
                res.json({ success: true, code: 200, response: csgo_data });
            });


        });

    }
    ])};

结果如下:

{"success":true,"code":200,"response":[{"steamid":"76561198013250658","re​​sponse":"76561198013250658 不是机器人的朋友..."},{" steamid":"76561198263874163","re​​sponse":"76561198263874163 不是 bot 的朋友..."},{"steamid":"76561198156967342","re​​sponse":"76561198156967342 不是 bot 的朋友..." }]}

调用的时候问题来了

csgo.requestPlayersProfile(steamid, function(result) {
console.log(result);
csgo_data.push(csgo_data, {steamid: steamid, response: result});});

console.log 的输出数据(例如:{"ID":"hello"})在终端上正确显示,但未推送到 csgo_data 数组...

请尝试给我一个解释:-)

【问题讨论】:

  • 您遇到错误了吗? TypeError: second argument to Function.prototype.apply must be an array ... 为什么你在做 csgo_data.push.apply(csgo_data, {steamid: steamid, response: result}); ... 而不是 csgo_data.push({steamid: steamid, response: result});
  • @JaromandaX 不,我没有收到任何错误。
  • 只是为了测试xd..我也试过csgo_data.push方法。
  • @JaromandaX 知道有什么问题吗?
  • 如果csgo.requestPlayersProfile 是异步的,回调中的push() 命令将在 res.json() 之后被调用

标签: javascript arrays node.js api express


【解决方案1】:

为了避免此类问题,我尝试在 Promises 上重写 forEach(..)。像这样:

steamClient.getPersonas(steamids, function(resp) {
            Promise.all(Object.keys(resp).map(
              (steamid)=>new Promise((resolve)=>{
                  if (!steamClient.myFriends.hasOwnProperty(steamid)) {
                      if (resp[steamid].game_played_app_id == 730) {
                            csgo.requestPlayersProfile(steamid, (result)=> {
                              console.log(result);
                              resolve({steamid: steamid, response: result});
                            });
                      }else{
                          resolve({steamid: steamid, response: steamid + " is not playing csgo"});
                      }                   
                  }else{
                      resolve({steamid: steamid, response: steamid + " Is not bot´s friend..."});
                  }
                })
             )  
           ).then((csgo_data)=>
            res.json({ success: true, code: 200, response: csgo_data })
           );
});

【讨论】:

  • 这还是有问题...如果对csgo.requestPlayersProfile函数的调用超过1次,就会发生...
【解决方案2】:

这是我的承诺版本:

// build Promise from steamid
function getData(steamid) {
  return new Promise((resolve, reject) => {
    var data = {
      steamid: steamid,
      response: steamid + " Is not bot's friend..."
    };
    if (!steamClient.myFriends.hasOwnProperty(steamid)) resolve(data);
    else if (resp[steamid].game_played_app_id != 730) {
      data.response = steamid + " is not playing csgo";
      resolve(data);
    } else {
      csgo.requestPlayersProfile(steamid, function(result) {
        console.log(result);
        data.response = result;
        resolve(data);
      });
    }
  });
}

// build array of promises and pass to Promise.all()
Promise.all(Object.keys(resp).map(steamid => getData(steamid)))
  .then(data => {
    res.json({
      success: true,
      code: 200,
      response: csgo_data
    });
  });

【讨论】:

  • 这还是有问题...如果对csgo.requestPlayersProfile函数的调用超过1次,就会发生...
  • @Alex 你是说你看到多个控制台输出但没有发送响应?
  • 我是说如果有多个玩家同时玩csgo,只会显示第一个结果。第一个数组项目正确显示(steamid),但第二个项目(csgo数据)在每个数组中重复。也许只是和错误......
  • 我需要另一种方式(系统)来完成这项工作......有什么想法吗?
  • @Alex 您需要更具体一些。你到底在控制台中得到了什么?发送回浏览器的 JSON 格式究竟是什么?我在代码中没有看到两个不同的数组,只有一个。理想情况下,将您的代码放在 github 上,这样我就不必为了发现一些小错误而构建自己的版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多