0

I have pretty complex logic on front-end for saving files to server:

1) Save file1
2) Save file2
3) Save file3

If file3 fails to save, file2 and file1 have to be reverted. Right now I'm using promises:

file1.save().then(file2.save).then(file3.save).

I just thought that there could be an implemenation for these cases sort of like transactions for database. Is there anything like that?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

1

what you need is some sort of endpoint in server to revert, I am going to leave the logic of that implementation to you, just using stubs file.save() for save and file.revert() for reverting, and assuming that both return promises:

var files = [file1, file2, file3, ...], revertFiles =[];
var promise = Promise.resolve();
files.forEach( file => 
    promise.then(() => file.save())
        .then(() => revertFiles.unshift(file))
);
promise.catch(e => revertFiles.forEach( file => promise.then( () => file.revert() )));

basically, whenever you finish some action, make a stack of actions for reverting that, and when you face some failure, just do all the actions stacked up in the queue.

Edit: in es5 style

var files = [file1, file2, file3, ...], revertFiles =[];
var promise = Promise.resolve();

files.forEach(function(file){
  promise.then(function(){
    return file.save();
  }).then(function(){
    revertFiles.unshift(file);
  });
});

promise.catch(function(e){
  revertFiles.forEach(function(file){
    promise.then(function(){
      return file.revert();
    });
  });
}); 
mido
  • 24,198
  • 15
  • 92
  • 117
  • thanks, I was actually asking about some sort of library, but your comment may be insightful as well. Can you rewrite your example in javascript? – Max Koretskyi Aug 31 '15 at 06:24