diff --git a/README.md b/README.md index f8afa6f..c889e11 100644 --- a/README.md +++ b/README.md @@ -60,3 +60,15 @@ orm.connect("mysql://username:password@host/database", function (err, db) { }); ``` +#### ES6: await/async +```js +await db.transactionAsync(async () => { + let persons = await Person.findAsync({ surname: "Doe" }) + + for (let person of persons) { + await person.removeAsync(); + } +}); +``` +**make sure use await in `db.transactionAsync` to catch error when function scope throw error** +**and make sure function scope use async and await to ensure commit, or catch error throw then to rollback** diff --git a/lib/plugin.js b/lib/plugin.js index 5ce316d..3adb0ac 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -28,6 +28,21 @@ function Plugin(db) { }); }; + db.transactionAsync = async function (cb) { + await db.driver.execQueryAsync("BEGIN"); + debug("init transaction!"); + + try { + await cb(); + debug("transaction committed!"); + await db.driver.execQueryAsync("COMMIT"); + } catch(err) { + debug("transaction rolled back!"); + await db.driver.execQueryAsync("ROLLBACK"); + throw err; + } + } + return { define: function (Model) { }