Skip to content

Commit

Permalink
reversing parameters for tx factory.
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaly-t committed Apr 26, 2015
1 parent 065c6ee commit c130021
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 6 deletions.
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ to be executed inside a transaction, one by one, and if one fails - the rest won
architecture this can only be achieved by using a promise factory, which is exactly what it is.

```javascript
function txFactory(t, idx) {
function txFactory(idx, t) {
// must create and return a promise object dynamically,
// based on the index of the sequence (parameter idx);
switch (idx) {
Expand All @@ -386,6 +386,29 @@ db.tx(function (t) {
});
```

An inline version gets simpler, because the factory doesn't need to declare parameter `t`,
as it is available from the container:

```javascript
db.tx(function (t) {
return t.sequence(function (idx) {
switch (idx) {
case 0:
return t.query("select 0");
case 1:
return t.query("select 1");
case 2:
return t.query("select 2");
}
});
})
.then(function (data) {
console.log(data); // print result;
}, function (reason) {
console.log(reason); // print error;
});
```

Such approach guarantees strict sequence of queries execution by turning an otherwise asynchronous
queue of queries into a synchronous one, which is a price to consider.

Expand Down
2 changes: 1 addition & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ function $sequence(t, factory) {
function loop(factory, idx, result) {
var obj;
try {
obj = factory(t, idx); // get next promise;
obj = factory(idx, t); // get next promise;
} catch (e) {
return $p.reject(e.message || e);
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pg-promise",
"version": "1.0.5",
"version": "1.0.6",
"description": "PG + Promises/A+, with transactions.",
"main": "lib/index.js",
"scripts": {
Expand Down
6 changes: 3 additions & 3 deletions test/dbSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -638,12 +638,12 @@ describe("Transaction sequencing", function () {
it("must resolve promises in correct sequence", function () {
var result;
db.tx(function (t) {
return t.sequence(function (tx, idx) {
return t.sequence(function (idx) {
switch (idx) {
case 0:
return tx.query("select 'one' as value");
return t.query("select 'one' as value");
case 1:
return tx.query("select 'two' as value");
return t.query("select 'two' as value");
}
});
}).then(function (data) {
Expand Down

0 comments on commit c130021

Please sign in to comment.