I've been trying to find out how to make sequelize work with 'async' and 'await'.
The best information I could find on that topic was an answer in this thread:
Node.js 7 how to use sequelize transaction with async / await?
But I can't quite make it work in my project. I've been cutting out parts of code to make it simpler so I can work out what exactly is not right and ended up with something like this:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('zas', 'zas', 'saz123',
{
host: 'someHost',
dialect: 'mysql',
}
);
//test
let transaction;
var SimpleInspectionModel = require('../models/simpleInspectionModel.js')(sequelize, { dataTypes: Sequelize.DataTypes } );
try {
// get transaction
transaction = await sequelize.transaction();
// step 2
await SimpleInspectionModel.find({}, {transaction});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction if any errors were encountered
await transaction.rollback();
}
Whenever run, this code will output this kind of error :
transaction = await sequelize.transaction();
^^^^^
SyntaxError: await is only valid in async function
at createScript (vm.js:80:10) at Object.runInThisContext
(vm.js:139:10) at Module._compile (module.js:616:28) at
Object.Module._extensions..js (module.js:663:10) at Module.load
(module.js:565:32) at tryModuleLoad (module.js:505:12) at
Function.Module._load (module.js:497:3) at Function.Module.runMain
(module.js:693:10) at startup (bootstrap_node.js:191:16) at
bootstrap_node.js:612:3
Project dependencies in package.json:
body-parser: ^1.18.3
express: ^4.16.3,
express-session: ^1.15.6,
file-system: ^2.2.2,
mysql2: ^1.5.3,
sequelize: ^4.37.10
Node v8.11.3