【问题标题】:NodeJS can't await MySQL database promise, but awaits other promisesNodeJS 不能等待 MySQL 数据库承诺,而是等待其他承诺
【发布时间】:2021-10-10 02:36:57
【问题描述】:
let static_times_generate = async (static_file_path) => {
    //Import MySQL database pool connection:
    const db = require('../database_pool.js');
    const Promise_pool = db.promise();

    //Import Static Text file dependencies:
    const { readFile } = require('fs/promises') , stop_times = static_file_path+'/stop_times.txt', trips = static_file_path+'/trips.txt';

    let trip_data = (await readFile(trips,'utf8')).split('\n').slice(1,2);
    let stop_times_data = (await readFile(stop_times,'utf8')).split('\n').slice(1,-1);

    trip_data.forEach(trip_line => {
        const t_array = trip_line.split(',');
        stop_times_data.forEach(st_line =>{
            const st_array = st_line.split(',');

            if(st_array[0] == t_array[2]){
                if(t_array[1] == 'SundaySum'){ t_array[1] = 'Sunday' } 
                else if(t_array[1] == 'SaturdaySum'){ t_array[1] = 'Saturday' }
            
//Here is the issue
            await Promise_pool.execute(`INSERT INTO static_times (1, 2, 3, 4, 5, 6, 7) VALUES (?,?,?,?,?,?,?)`
            ,[elm1,elm2,elm3,elm4,elm5,elm6,elm7] )
            }
        });
    });

    console.log("COMPLETED!")
    
}
static_times_generate('./mysql_table_generators/STATIC_FILES'); //This is how i'm calling the function

我读取文件并将某些数据推送到 MySQL 数据库中,为此我使用节点 mysql2。

    let trip_data = (await readFile(trips,'utf8')).split('\n').slice(1,2);
    let stop_times_data = (await readFile(stop_times,'utf8')).split('\n').slice(1,-1);

readFile 承诺正在等待中,但是当涉及到 Promise_pool 查询时,它给出了错误:

            await Promise_pool.execute(`INSERT INTO static_times (routeId, serviceId, tripId, stopId, arrivalTime, orientation, tripHeadsign) VALUES (?,?,?,?,?,?,?)`
            ^^^^^

SyntaxError: await is only valid in async function
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

我已经在我的代码的其他文件中完成了这种等待,并且它有效,为什么它不能识别等待被包装在异步函数中? (我也试过 await db.execute 方法,没有使用 db.promise() 原型)

这是我的 database_pool.js 文件

const mysql = require('mysql2');

const db_pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'drt_sms_db',
    multipleStatements: true
});

module.exports = db_pool;

*** 是的,我知道我不需要需要等待,但是我将 100 万行插入到我的数据库中,所以我收到了 MySQL ETIMEOUT 错误。 await 是我目前唯一的选择。

【问题讨论】:

    标签: mysql node.js asynchronous ecmascript-6 async-await


    【解决方案1】:

    您的 await 调用范围仅限于 forEach 回调函数。如果你想使用 await,你可以像这样将 async 添加到 forEach 回调中:

    stop_times_data.forEach(async (st_line) => {
       await doSomething();
    }
    

    话虽如此,这里的回调函数实际上并不等待承诺完成,因为forEach 只接受同步函数。查看here 了解更多详情。如果您需要等待一个请求完成后再发送另一个请求,您应该改用for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2013-09-16
      • 2018-03-19
      • 2019-12-10
      • 1970-01-01
      • 2022-11-26
      • 2021-11-26
      相关资源
      最近更新 更多