0

I need to execute the go() method when the promise is fulfilled, even if there is an error. (I am talking to backend API, and I need to do some UI work when I have the server response, even if is a 404).

Now I do this way:

Try.method().then(()=>{
  go();
}).catch({
  go();
})

There is a better way to avoid repeating the method invocation?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ciaoben
  • 3,138
  • 4
  • 27
  • 42

2 Answers2

2

There is a finally() callback which will be called no matter what the outcome is:

Try.method().then(()=>{
  go();
}).catch({
  go();
}).finally({
  go();
});

Since you are using babeljs which doesn't appear to support the finally() callback you can probably get away with this:

Try.method().catch(()=>{
  go();
}).then({
  go();
})

Where you first catch an error if there is one, if not it will execute the .then() as usual.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
0

There is a better way to avoid repeating the method invocation?

Not certain if interpret above portion of Question correctly ? Try defining a separate .then(go, go) chained to end of api calls

var go = function(data) {
  console.log("go", data)
};

var p = function(args, val) {
  return Promise[args](val)
};

p("resolve", 1).then(go, go);

p("reject", 0).then(go, go);

If can use jQuery, could try utilizing deferred.always()

var go = function(data) {
  console.log("go", data)
};

var p = function(args, val) {
  return $.Deferred()[args](val)
};

p("resolve", 1).always(go);

p("reject", 0).always(go);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
guest271314
  • 1
  • 15
  • 104
  • 177