0

我向我的快递服务器提交了一个表格,我收到以下错误:

TypeError: Cannot read property 'then' of undefined

“then”指的是下面(截断)代码中的 then(控制器文件中的 post 方法)。

exports.postAddVehicle = (req, res, next) => {
    //const id = null;
    //car table
    const model_year = req.body.model_year;
    const make = req.body.make;
    ...
    const car = new Car(
        null, model_year, make, model, 
        miles, color, transmission, layout, engine_type,
        car_photo_url, car_price, sale_status, for_sale);
        console.log(car);
    car
        .save()
        .then(() => {
            res.redirect('/');
        })
        .catch(err => console.log(err))
}

save 方法是一种模型方法/我第一次尝试在模型中使用 mysql2 npm 包进行事务:

        save() {
            db.getConnection()
                .then((db) => {
                    return db.query('START TRANSACTION');                    
                })
                .then(() => {
                    db.query('INSERT INTO cars (model_year, make, model, color, miles, transmission, layout, engine_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                    [this.model_year, this.make, this.model, this.color,this.miles, this.transmission, this.layout, this.engine_type])
                })
                .then(() => {
                    db.query('INSERT INTO car_photos (car_photo_url) VALUES (?)',
                    [this.car_photo_url])
                })
                .then(() => {db.query('INSERT INTO car_price (car_price) VALUES (?)', [this.car_price])
                })
                .then(() => {db.query('INSERT INTO sales_status (sale_status, for_sale) VALUES (?, ?)', [this.sale_status, this.for_sale])
                })
                .then(() => {
                    return db.query('COMMIT');
                })
                .catch((error) => {
                    return db.query('ROLLBACK');
                })
        }

有什么问题?

4

1 回答 1

1

save()方法应该返回一个 Promise,因此您可以在链中调用.thenand 。.catch

请尝试类似:

save() {
    return db.getConnection()
    ...
}
于 2021-09-18T02:54:05.887 回答