简体   繁体   中英

How can I start the next row after the first one is completed?

I want to send and receive some information from the CS:GO GC, with my current script I send all request at one time, but I want some delay inbetween these requests (1000 - 2000ms maybe) so that every request is going through.

The best way for this could be like that the row is starting and when it got the data it requested, then the second row is starting... and so on.

My current code looks like this (simplified it a bit):

    pool.getConnection(function(err, connection) {
      if (err) throw err;
      connection.query("SELECT * FROM Users WHERE SteamID64 IS NOT NULL", function (err, rows, fields) {
        connection.release();
        if (err) throw err;
        rows.forEach( (row) => {

      //Request Data from CS:GO
      csgo.requestPlayersProfile(SteamID64, function(ranking) {
          var rankid = ranking.ranking.rank;
          var wins = ranking.ranking.wins;
          var private = ranking.player_level;

          console.log("=================================");
          console.log("SteamID: " + `${row.SteamID64}`);
          console.log("Rank: " + rank);
          console.log("Wins: " + wins);
          console.log("Private Rank: " + private);
          console.log("=================================");
      });
    });
  });
});

I would convert the callback style function to promise style and use async/await . Similarly wrap setTimeout in promise and use that to add wait in between

async function requestPlayersProfile(SteamID64) {
  return new Promise((resolve, reject) => {
    csgo.requestPlayersProfile(SteamID64, function(ranking) {
      resolve(ranking);
    });
  });
}

async function wait(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

pool.getConnection(function(err, connection) {
  if (err) throw err;
  connection.query("SELECT * FROM Users WHERE SteamID64 IS NOT NULL", async function(
    err,
    rows,
    fields
  ) {
    connection.release();
    if (err) throw err;
    for(const row of rows) {
      const ranking = await requestPlayersProfile(ow.SteamID64);
      var rankid = ranking.ranking.rank;
      var wins = ranking.ranking.wins;
      var private = ranking.player_level;

      console.log("=================================");
      console.log("SteamID: " + `${row.SteamID64}`);
      console.log("Rank: " + rank);
      console.log("Wins: " + wins);
      console.log("Private Rank: " + private);
      console.log("=================================");

      await wait(1000);
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM