3

So I have 2 promise functions. When there is an error for the first function I want it to display an error message. When either complete or fail I would like them to execute a finally catch all function but for some reason it isn't working. my code looks like this:

// If our garment has a logo
shared.logoExists(garment, model).then(function () {

    // Save our panel
    return shared.save(model);

// If there was an error
}, function () {

    // Display an error message
    toastr.warning(localization.resource.logoPlacementError.message);

// Always close the library
}).finally(function () {

    // Reset our attachments
    self.resetAttachment();

    // Hide our library
    self.closeLibrary();
});

So basically what I am trying to achieve is if the first function fails, it will display and error. When the second function fails, it won't do anything. But if either succeed or fail, it will always close the library.

Does anyone know how I can achieve this?

r3plica
  • 13,017
  • 23
  • 128
  • 290

3 Answers3

1

You have to use .catch after closing the then function:

// If our garment has a logo
shared.logoExists(garment, model).then(function () {

    // Save our panel
    return shared.save(model);

// If there was an error
}).catch(function () {

    // Display an error message
    toastr.warning(localization.resource.logoPlacementError.message);

// Always close the library
}).finally(function () {

    // Reset our attachments
    self.resetAttachment();

    // Hide our library
    self.closeLibrary();
});
Jaime Still
  • 1,949
  • 20
  • 31
  • Doesn't explain why *"you have to use catch"*. Nothing being returned in `catch` so realistically there isn't much effective difference here – charlietfl Mar 04 '16 at 14:30
  • The structuring of the promise pattern could be causing the finally function not to be called. Just a thought for something to try. And the way his code was structured, he wants to be able to identify if there was an error, hence the catch function. – Jaime Still Mar 04 '16 at 14:31
  • Big difference between *"you have to use"* and ... *"try this"*. There are good supporting arguments for using catch instead of second argument of then though but they aren't mentioned here – charlietfl Mar 04 '16 at 14:33
  • 1
    Then feel free to provide them. – Jaime Still Mar 04 '16 at 14:35
0

Depending on which version of Angular you're using, you may have to use "always" instead of "finally". Try "always" and see if it works.

How to always run some code when a promise is fulfilled in Angular.js

Community
  • 1
  • 1
FrancisA
  • 146
  • 1
  • 9
0

It turns out that my way works fine. The logoExists function was not resolving / rejecting a promise in all places that it should be. When I fixed that, my code above worked.

r3plica
  • 13,017
  • 23
  • 128
  • 290