最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在 node.js 中的 while 循环期间使用某种暂停或设置超时

网站源码admin32浏览0评论

在 node.js 中的 while 循环期间使用某种暂停或设置超时

在 node.js 中的 while 循环期间使用某种暂停或设置超时

我正在使用 bluellinky 来跟踪我的汽车数据。

我设法从服务器获取数据并将其上传到数据库。 现在我需要某种“暂停”,因为数据以错误的顺序完成。你能帮我添加这个吗?

这是我的代码:
// Use the MariaDB Node.js Connector and run npm install mariadb
const mariadb = require('mariadb');
const { kill } = require('process');

// Create a connection pool
const pool = 
  mariadb.createPool({
    host: 'host', 
    port: port,
    user: 'user', 
    password: 'password',
    database: 'db'
});


//Bluelinky verbinden
const BlueLinky = require("bluelinky");


const client = new BlueLinky({
  username: 'user',
  password: 'password',
  brand: 'brand', // 'hyundai', 'kia'
  region: 'country', // 'US', 'EU', 'CA'
  pin: 'pin'
});



//get yesterdays date
const repdate = new Date();
repdate.setDate(repdate.getDate()-1); // -1 => yesterday, blank => today 



// called when the client logs in successfully
client.on("ready", async () => {
  const vehicle = client.getVehicle("carnumber");
  const trpInfo = await vehicle.tripInfo({year: repdate.getFullYear(), month: repdate.getMonth()+1, day: repdate.getDate()});



if (trpInfo != '') 
    {
  
  //Erstelle Datum
  const tripdaydateraw = trpInfo[0].dayRaw.slice(4,6) + '/' + trpInfo[0].dayRaw.slice(6,8) + '/' + trpInfo[0].dayRaw.slice(0,4);
  const tripdaydate = trpInfo[0].dayRaw.slice(0,4) + '-' + trpInfo[0].dayRaw.slice(4,6) + '-' + trpInfo[0].dayRaw.slice(6,8);
  const tripdaynameraw = new Date(tripdaydateraw).toLocaleDateString('de-de', {weekday: 'long'});
  const tripdayname = tripdaynameraw;
    //Erstelle Anzahl der Fahrten
  const tripdayCnt = trpInfo[0].tripsCount;
  //Erstelle Tagesdistanz
  const tripdayDistance = trpInfo[0].distance;
  //Erstelle Tagedurchschnittsgeschwindigkeit
  const tripdayavgSpeed = trpInfo[0].speed.avg;
  //Erstelle maximale Tagesgeschwindigkeit
  const tripdaymaxSpeed = trpInfo[0].speed.max;
  
  // Errechne Anzahl der Fahrten
  let n = 0, i = tripdayCnt - 1


  while(n <= i) {
      //Restliche Werte definieren

      //Erstelle Durchschnittsgeschwindigkeit Fahrt
      const tripavgSpeed = trpInfo[0].trips[i].speed.avg;
      //Erstelle maximal Fahrgeschwindigkeit
      const tripmaxSpeed = trpInfo[0].trips[i].speed.max;
      //Startzeit
      const strttimstamp = trpInfo[0].trips[i].start;
      //Enzeit
      const endtimstamp = trpInfo[0].trips[i].end; 
      //Startdatum
      const strtdate = strttimstamp.toLocaleDateString();
      //toLocaleTimeString konvertiert GMT + 1, Startzeit
      const strtime = strttimstamp.toLocaleTimeString() ;
      //Enddatum
      const enddate = endtimstamp.toLocaleDateString();
      //toLocaleTimeString konvertiert GMT + 1, Endzeit
      const endtime = endtimstamp.toLocaleTimeString();

      //Fahrzeit in Minuten
      const drvtime_minutes = trpInfo[0].trips[i].durations.drive;

      //Stehzeit in Minuten
      const idletime_minutes = trpInfo[0].trips[i].durations.idle;

      //Distanz
      const drvdistance = trpInfo[0].trips[i].distance;

      //Tankrechnung
      const refuel_amt = '0.00'

      //Werte Ausgeben
      const tripinfodata = tripdaydate + ', ' + tripdayCnt + ', ' + tripdayDistance + ', ' + tripdayavgSpeed + ', ' + tripdaymaxSpeed + ', ' + tripavgSpeed + ', ' + tripmaxSpeed + ', ' + strtime + ', ' + endtime + ', ' + drvtime_minutes + ', ' + drvdistance + ', ' + tripdayname;
      
      //SQL Statement bauen
      let connection

      try {
      connection = await pool.getConnection()
      } catch(error) {
        //not connected
        pool.end()
        return // or: log and/or throw error again
      }

      // run insert query
      const queryString = "INSERT INTO nightfury_trips (tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
      const queryData = [tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt]

      let rowsInserted
      try {
        rowsInserted = connection.query(queryString, queryData)
      } catch (error) {
        // handle error
        console.log(error);
        connection.end();
        
        // continue on the next loop
        n -= 1;
        continue;
      }
  
      // rows inserted successfully, log them
      console.log(rowsInserted)
      
      n -= 1
    }
  
    pool.end()
    console.log('finished!')
  }
  
  // call myLoop.
  // this is an async function
  myLoop()
    .then(() => console.log('myLoop finished!'))
    .catch((error) => console.error('unexpected error:', error))
});

更新 04.05.2023 22:14

感谢@dave newton 的快速响应。结果看起来像这样:

2023-05-04, 2, 3, 41, 89, 35, 60, 20:37:02, 20:42:02, 5, 2, Donnerstag
2023-05-04, 2, 3, 41, 89, 47, 89, 07:49:48, 07:52:48, 3, 1, Donnerstag

但我想反过来,按时间戳升序排序;这就是为什么我使用“i -= 1”,但它并不总是有效,我认为这是因为现代服务器和我的机器之间的滞后。

更新 06.05.2023 08:06

@tmilar:多亏了你,但我现在有多次返回的问题,例如,昨天我开车四次,但日志给了我 10 次

PS C:\Users\Josi\Downloads\bluelinky> node nightfury_trip_DBupload_sorted.js
Register request has failed with Error=PHONE_REGISTRATION_ERROR
Retry... 1
Register request has failed with Error=PHONE_REGISTRATION_ERROR
Retry... 2
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
回答如下:

问题是您正在运行调用以将数据存储在数据库中,这是一个 Promise / async 操作,在

while
循环内,而没有使用任何机制在每次下一次循环迭代之前等待操作完成。

解决这个问题的方法是使用 async/await 运算符。

这是一个基本的例子:

async function myLoop() {

  // ... some initial logic
  
  while (n <= i) {

    // ... logic to read your data for this loop iteration goes here

    // retrieve connection
    let connection 
  
    try {
      connection = await pool.getConnection()
    } catch(error) {
      // not connected
      pool.end()
      return // or: log and/or throw error again
    }
    
    // run insert query
    const queryString = "INSERT INTO nightfury_trips (tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
    const queryData = [tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt]

    let rowsInserted
    try {
      rowsInserted = connection.query(queryString, queryData)
    } catch (error) {
      // handle error
      console.log(error);
      connection.end();
      
      // continue on the next loop
      n -= 1;
      continue;
    }

    // rows inserted successfully, log them
    console.log(rowInserted)
    
    n -= 1
  }

  pool.end()
  console.log('finished!')
}

// call myLoop.
// this is an async function
myLoop()
  .then(() => console.log('myLoop finished!'))
  .catch((error) => console.error('unexpected error:', error))
发布评论

评论列表(0)

  1. 暂无评论