简体   繁体   中英

AngularJS chained promises and finally callback

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?

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();
});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM