Having accepted Benjamin Grunbaum’s recommendation to use the deletion pattern, here is one written as an adapter method for Workqueue.instance() :
Workqueue.transaction = function (work) {
Now you can write:
// if the order mattters, // then add promises sequentially. Workqueue.transaction(function(queue) { var work1 = new Work(); var work2 = new Work(); return queue.add(work1) .then(function() { return queue.add(work2); }); }); // if the order doesn't mattter, // add promises in parallel. Workqueue.transaction(function(queue) { var work1 = new Work(); var work2 = new Work(); var promise1 = queue.add(work1); var promise2 = queue.add(work2); return Promise.all(promise1, promise2); }); // you can even pass `queue` around Workqueue.transaction(function(queue) { var work1 = new Work(); var promise1 = queue.add(work1); var promise2 = myCleverObject.doLotsOfAsyncStuff(queue); return Promise.all(promise1, promise2); });
In practice, an error handler should be included as follows: Workqueue.transaction(function() {...}).catch(errorHandler);
All you write, all you have to do is make sure that the callback function returns a promise, which is the collection of all component asynchronizations (component promises). When the collective promise is resolved, the manager will ensure that the transaction is completed.
Like all stewards, this one does nothing that you cannot do without it. However, this:
- serves as a reminder of what you are doing by providing a named
.transaction() method, - applies the concept of a single transaction, restricting
Workqueue.instance() to one commit.
If for some reason you ever need to execute two or more transactions in the same queue (why?), You can always return directly to the Workqueue.instance() call.
source share