From 3936b3d93f1299bb2a0157399203aff2cead38c9 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Thu, 3 May 2018 14:45:32 +0800 Subject: [PATCH 1/3] add async func for es6 --- lib/plugin.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/plugin.js b/lib/plugin.js index 5ce316d..4c1bcf1 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -28,6 +28,20 @@ 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"); + } + } + return { define: function (Model) { } From 9f364278e21be255834a79eec3fe85be795e691a Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Thu, 3 May 2018 15:01:40 +0800 Subject: [PATCH 2/3] should throw error --- lib/plugin.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/plugin.js b/lib/plugin.js index 4c1bcf1..3adb0ac 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -39,6 +39,7 @@ function Plugin(db) { } catch(err) { debug("transaction rolled back!"); await db.driver.execQueryAsync("ROLLBACK"); + throw err; } } From a7ec42778b6e3a8c30a05fe9e5012cb0652d44fc Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Fri, 1 Jun 2018 11:56:39 +0800 Subject: [PATCH 3/3] add readme --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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**