Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async transactions in javascript

Tags:

javascript

First of all rollback is something that I do not care about.

I would like to be able to lock a sequence of async functions/promises/tasks (let's call it a "transaction") with a name/id (or array of names), so that they happen in sequence, and so that any other "transaction" with the same name(s) that are run by another part of the system are delayed from starting until the running transaction using the same name(s) has completed. So it basically is queueing the sequences of async tasks, or "transaction"s.

Here is some example code of the situation:

function a()
{
  // do stuff
  return new Promise(/*...*/);
}


function b()
{
  // do stuff
  return new Promise(/*...*/);
}



function c()
{
  // do stuff
  return a.then(() => b());
}

Now at any time the system could call a, b, or c, and when it does I don't want c and b running at the same time, but obvious c depends on b.

I've been looking for a package on npm to help with this but I haven't found anything, I wonder if anyone can suggest something that I might have missed that would help with this?

like image 684
erikvold Avatar asked May 13 '17 05:05

erikvold


1 Answers

I think gulp tasks can help you out of the box. This guarantees that c always run after b and so b after a

const gulp = require('gulp');
gulp.task('a', done => {
  // do stuff
  console.log('a');
  done();
});

gulp.task('b', ['a'], done => {
  // do stuff
  console.log('b');
  done();
});

gulp.task('c', ['b'], done => {
  // do more stuff
  console.log('c');
  done();
});

gulp.start('c'); // Logs a, b, c

Try it!

like image 118
Mouneer Avatar answered Oct 04 '22 21:10

Mouneer