异步等待递归在mysql查询完成之前提前执行

3mpgtkmj  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(244)

实际上,我正在运行一个函数,该函数运行一个查询来检查mysql表中的数据是否过期。
如果过期,它将运行一个单独的函数来清除表(truncate),然后追加新数据。在这个单独的函数之后,主函数递归。
清除和追加所有新数据的函数:

let db_insert_realtime = async () => {

  try {
    var result = await read_gtfs('https://path_to_gtfs_file');
  } catch (err) {
    console.log(err);
  }

  //Clears table realtime_gtfs
  await db.query('TRUNCATE TABLE realtime_gtfs');

  for (let r of result.entity) {
    for (let STU of r.tripUpdate.stopTimeUpdate) {

      await db.query(`INSERT INTO realtime_gtfs 
                    SET expiryTime = ? ,
                     routeId = ? ,
                     vehicleId = ? ,
                     arrivalTime = ? ,
                     stopId = ?`,
        [parseInt(Math.floor((Date.now() + 90000) / 1000)),
        data[1],
        data[2],
        data[3],
        data[4]
        ]);
    }
  }
  console.log("Completed!")

};

所以在这个函数中:
等待要读取的文件(在http链接上使用read_gtfs),此read_gtfs函数使用承诺解析。
之后,它截断表(以清除它)(使用wait)
最后,它附加所有新数据。在最后一步中,我尝试了等待查询(如上所示),还尝试了常用的node-mysql方法:

db.query('SQL command = ? ',[data], (err,res) => {});

运行查询以检查表中数据是否过期的主函数。。

let gtfs_parse = async (stop_number, state) => {
    /* A false state means that the function hasn't checked if the data is expired or not 
        NOTE: the state is initally false.
    */
    if(state == false){
        const init_data = await query('SELECT * FROM `realtime_gtfs` LIMIT 1');
        const current_time = parseInt(Math.floor((Date.now()) / 1000));

        if (current_time >= init_data[0].expiryTime ) {
            await gtfs_rt.db_insert_realtime();   
        }
        await gtfs_parse(stop_number,true);

    } else {
        console.log("gets here??")
        const count = await query('SELECT COUNT(*) FROM realtime_gtfs');
        console.log(count);
        const stopData = await query('SELECT * FROM `realtime_gtfs` WHERE stopId = ?', [stop_number]);
        console.log(stopData)
    }

}

gtfs_parse(2242,false);

stopid参数是数据库将在函数中解析的任意值(仅当数据未过期时)。状态只是检查是否检查了旧数据(false表示未检查,true表示已检查)
问题是:当数据过期时,它会成功地递归,但是来自新数据的响应是空的,因为表还没有更新。
错误消息:

MySQL is loaded!
Length of GTFS file: 162
sql_append_query: 88.931ms  <-- appending the new data in the MySQL table
Completed!

gets here?? <-- Recursion
[ RowDataPacket { 'COUNT(*)': 0 } ] <-- As you can see, 0 rows, meaning the sql_append_query is sitll running?
[] <--- That's the stopData response

然后,马上,我可以重新运行相同的函数,并得到所需的响应:

MySQL is loaded!
gets here??
[ RowDataPacket { 'COUNT(*)': 2497 } ]
[
 RowDataPacket {
   expiryTime: 1627308284,
   routeId: 900,
   vehicleId: 9103,
   arrivalTime: 1627306573,
   stopId: 2242
 },
 RowDataPacket {
   expiryTime: 1627308284,
   routeId: 900,
   vehicleId: 9100,
   arrivalTime: 1627310197,
   stopId: 2242
 },
.. 7 more
]

所以我肯定认为这个函数只是过早地重复出现,但是我几乎所有的函数都使用wait,所以它不应该这样做?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题