如何延迟请求数据?



我想创建一个 Steam 机器人,它正在从 CS:GO 请求玩家数据(我为此使用 node-globaloffensive(。 由于我从未用javascript做过一些事情,所以我只是尝试像在php中那样解决它。

所以我创建了一个与我的数据库的连接,做了一个forEach行。有一个问题,脚本同时请求所有数据,而我只取回了我的第一个数据。

所以我决定在 sleep(( 中添加一些延迟。 这有时实际上是有效的(以前它对 7 个请求没有问题,但现在它只发出 2 个并在 setInterval(( 之后再次重新启动它(,但即便如此,有时也不是......这就是为什么我现在想改进我的代码,以便我的机器人几乎可以正常工作,而且更干净。

这是我当前的代码:

const SteamUser = require('steam-user');
const SteamTotp = require('steam-totp');
const GlobalOffensive = require('globaloffensive');
const config = require('./config');
const db = require('./database');
var SteamID = require('steamid');
var mysql = require('mysql');
let user = new SteamUser();
let csgo = new GlobalOffensive(user);
csgo.on('debug', console.log);
user.on('error', console.error);
var pool  = mysql.createPool({
supportBigNumbers     : true,
bigNumberStrings      : true,
connectionLimit     : 100,
connectTimeout      : 20000,
acquireTimeout      : 20000,
host                : db.host,
user                : db.user,
password            : db.password,
database            : db.dbname
});
const logInOptions = {
accountName: config.accountName,
password: config.password
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
user.logOn(logInOptions);
user.on('loggedOn', res => {
console.log("Logged into Steam as " + user.steamID.getSteam3RenderedID());
user.setPersona(SteamUser.EPersonaState.Online);
user.gamesPlayed(730);
});
csgo.on("connectedToGC", function() {
console.log("connectedToGC");
const checkData = setInterval(()=>{
//Delete friends from list if they are not in a official Steamgroup
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query("SELECT * FROM Users WHERE SteamGroup1 = '0'  && SteamGroup2 = '0''", function (err, rows, fields) {
connection.release();
if (err) throw err;
rows.forEach( (row) => {
console.log(`${row.SteamID64}` + " got kicked.");
user.chatMessage(`${row.SteamID64}`, "You got kicked, because you're not in an official Steamgroup");
sleep(5000);
user.removeFriend(`${row.SteamID64}`);
});
sleep(500);

//Check connection to game coordinator
if ( csgo.haveGCSession ) {
//Check Database
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query("SELECT * FROM Users WHERE (MainSteamGroup = '1' || CommunitySteamGroup = '1' || vip = '1') && BotInFriendlist = '1'", function (err, rows, fields) {
connection.release();
if (err) throw err;
rows.forEach( (row) => {
sleep(1000);
var account_id = new SteamID(`${row.SteamID64}`);
console.log(account_id);
//Request Data from CS:GO
csgo.requestPlayersProfile(account_id, function(ranking) {
var rankid = ranking.ranking.rank_id;
var wins = ranking.ranking.wins;
var private = ranking.player_level;
console.log(rankid);
console.log(wins);
console.log(private);
sleep(1000);
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query("UPDATE Users SET CSGOMM = '" + rankid + "', CSGOWins = " + wins + ", CSGOPrivate = " + private + " WHERE SteamID64 = " + `${row.SteamID64}` + "");
connection.release();
});
});
});
});
});
};
});
});
}, 100000);
});

这就是它的样子:

Logged into Steam as [U:1:xxxxxxxxxx]
Sending GC message ClientHello
Sending hello, setting timer for next attempt to 2000 ms
Sending GC message ClientHello
Sending hello, setting timer for next attempt to 4000 ms
Got handled GC message ClientWelcome
Unknown SO type 2 with 1 items
Unknown SO type 7 with 1 items
GC connection established
connectedToGC
SteamID { universe: 1, type: 1, instance: 1, accountid: 2621xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 1591xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 1204xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 2886xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 1143xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 4421xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 1825xxxxx }
Sending GC message ClientRequestPlayersProfile
Got handled GC message PlayersProfile
Legendary Eagle Master
Got handled GC message PlayersProfile
Legendary Eagle Master
//and here it's just start again
SteamID { universe: 1, type: 1, instance: 1, accountid: 2621xxxxx }
Sending GC message ClientRequestPlayersProfile
SteamID { universe: 1, type: 1, instance: 1, accountid: 1591xxxxx }
Sending GC message ClientRequestPlayersProfile
...

我怎样才能改进我的forEach,所以也许它正在等待第一个请求结束,然后开始第二个请求,依此类推......

我想给你你需要的所有信息:)

我在你的代码中看到的一个问题是你正在使用一个循环来"睡眠",但这个循环会阻止你的服务器接收新请求,因为 javascript 是单线程的。

实现睡眠函数的更好方法是使用异步函数:

例:

const sleep = (time) => (
new Promise(resolve => setTimeout(resolve, time))
)
const asyncFunction  = async () => {
console.log("First task")
await sleep(1000)
console.log("Second Taks");
await sleep(3000)
console.log('Final task');
}
asyncFunction();

相关内容

  • 没有找到相关文章

最新更新