mysql2的Node Js,里面的promise函数没有按顺序执行

Nodejs with mysql2, promise functions in are not excuted in order

在我的 nodejs 应用程序中,我需要将数据写入我的 mysql 数据库,然后使用这些数据创建一个 PDF 文件,然后将此文件作为电子邮件附件发送。

generatePDF() 和 sendMail() 这两个函数是异步函数,因此,return 是一个承诺。我在 connection.query() 中调用这两个函数。我知道我必须使用承诺才能 运行 在执行 sendMail() 之前先生成 PDF() 但我无法让它工作。

我尝试使用,没有成功:

为清楚起见,我仅 post 部分代码。

const mysql = require('mysql2'); // I tried mysql2/promise as well


app.post('/HSF/calculator/register', async function (request, response) {
    var params = request.body;
    //console.log('params:',params);
    connection.query('INSERT INTO client_data SET ?', params, function (error, results, fields) {
        if (error) {
            throw error;
        }
        else {
                console.log('after .query(), before createOutputFile')
                var createOutputFile = `
                        SELECT
                                CONCAT("{",'"id":',
                                         JSON_OBJECT(
                                         "clientID",clientID,"name",name,"email",email,"age",age,"currentWeight",currentWeight,"weightUnit",weightUnit,"goalWeight",goalWeight,
                                         "height",height,"goalDate",goalDate,"mealsPerDay",mealsPerDay,"activityLevel",activityLevel,"eatingStyle",eatingStyle,"nutritionalRatio",
                                         nutritionalRatio,"workoutLevel",workoutLevel)
                                ,"}")
                                AS json FROM HerSoulFit.client_data
                                WHERE fileCounter = ${params.fileCounter}
                                INTO OUTFILE '/var/lib/mysql-files/data_${params.fileCounter}.json';`
                        connection.query(createOutputFile, (error, results) => {
                                if (error) {
                                        throw error
                                }
                                else {
                                        response.end(JSON.stringify(results));
                                }
                        })
                        await PDF.generatePDF(params.fileCounter)
                        await nodemailer.sendMail(params.name, params.email, params.fileCounter)
                        // does not work: PDF.generatePDF(params.fileCounter).then(nodemailer.sendMail(params.name, params.email, params.fileCounter))

       });
});

```

 

async 关键字位置错误。删除它并更改此行:

connection.query('INSERT INTO client_data SET ?', params, function (error, results, fields) {

connection.query('INSERT INTO client_data SET ?', params, async function (error, results, fields) {

我确认生成PDF解析时调用sendMail会更好

我相信您必须更改此行:

connection.query('INSERT INTO client_data SET ?', params, function (error, results, fields)

到这一行:

await connection.query('INSERT INTO client_data SET ?', params, async function (error, results, fields)

这将等待 post 调用的连接,然后您可以在查询中等待匿名函数。

猜测而已