Promote rejection if promise returns an error, from within .fail ()

I have the following code snippet:

var myFunc = function(id, obj, backupObj) { return update(obj) // this returns a promise .fail(function(err){ // if update is rejected restore(id, backupObj); // i wish to run this // and return the error that 'update(obj)' threw and propagate it return Q.reject(err); // should it be thrown like this??? }); } 

Is this the correct way to handle update() failure and returns an error, so when myFunc() is called from anywhere, can it be propagated and finally handled? For example, executed inside a chain:

 var foo = function(id, obj) { var backupObj = {}; return checkIfValidObj(obj) .then(function(_backupObj) { backupObj = _backupObj; return doSomethingElse(id, obj); }) .then(function() { // here! return myFunc(id, obj, backupObj); }); } 

And then, as the caller of foo , I would like to handle some errors and catch the error that update(obj).fail() can return:

 foo() .then(function() { /* everything worked as expected, so we are happy */ }) .catch(function(err){ // I want this to be executed also if 'update(obj)' inside 'myFunc' was rejected! }); 
+5
source share

Source: https://habr.com/ru/post/1236959/


All Articles