【问题标题】:Nodejs async.eachSeriesNodejs async.eachSeries
【发布时间】:2017-09-22 12:21:00
【问题描述】:

几个月前我问了几个关于这个的问题,最近我又回到了那个脚本。我想出了一些办法,一位朋友帮助编写了脚本,但现在我遇到了另一个问题。

这是我现在的脚本:

var j = schedule.scheduleJob('*/5 * * * * *', function(){
    var steamids = [];

    con.query("SELECT * FROM counterStrikeGlobalOffensive", function (err, rows) {
        for (var i = 0; i < rows.length; i++) {
            steamids.push(rows[i].steam64ID);
        }

        //const steamIDs = ["2342342341234123", "23423412341234", "2342314123423"]; // Steam IDs to check
        eachSeries(steamids, (steamID, callback) => {
            CSGOCli.playerProfileRequest(CSGOCli.ToAccountID(steamID));    
            CSGOCli.on("playerProfile", function(profile) {
                        console.log(JSON.stringify(profile, null, 2));
                        callback();
            });
        }, (err) => {
           // error thrown = set, else we're done
        });
    });
});

当我使用常量 steamID 时,它运行良好,但是当我使用 steamids 时,它给了我一个错误。(我会解释)...

当我这样做时,console.log(steamids);它返回给我这个

[ '76561198152643711', '76561198213530057' ]

steamID 是

const steamIDs = ["2342342341234123", "23423412341234", "2342314123423"];

所以它与常量 SteamID 几乎相同,但常量在数字周围有“”,这不应该是它不起作用的原因,但也许我错了?

另外,我有回调(),但我怎样才能让它停止给我一个错误 错误:回调已被调用。

请询问任何其他信息:)

【问题讨论】:

  • 我的建议是放弃 async 模块并使用原生或 Bluebird PromisesAsync-Await
  • 是的,这太复杂了,因为我使用 node js 大约 2 天,仅此而已。

标签: node.js


【解决方案1】:

您会得到Error: Callback was already called.,因为CSGOCli.on() 被执行了多次。所以它调用了一次回调,然后事件再次触发。所以回调被再次调用,但它应该只被调用一次。

对于一个简单的复制看这个例子:

async.eachSeries([1, 2, 3], (data, callback) => {
  console.log("Data:", data);
  for(let i = 0; i < 2; i++) {
    callback();
  }
},
(err) => {
  console.log("Callback: ", err);
});

但是如果你像这样在回调之前添加return:return callback();,那么问题就消失了,因为函数将返回并且不会再次调用回调。

所以把你的代码改成这个,看看它是否有效:

CSGOCli.on("playerProfile", function(profile) {
            console.log(JSON.stringify(profile, null, 2));
            return callback();
});

【讨论】:

  • 所以我按照你说的做了,它有效,但我仍然得到 /root/node_modules/async/dist/async.js:903 if (fn === null) throw new Error("Callback已经被调用了。");错误:回调已被调用。
  • 也许尝试在命令之前添加一个返回:return CSGOCli.on("playerProfile", ...
猜你喜欢
  • 2022-01-09
  • 2014-07-14
  • 2016-06-22
  • 2014-10-31
  • 2018-02-09
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多