Home:ALL Converter>SweetAlert2 and promises

SweetAlert2 and promises

Ask Time:2017-11-19T02:07:07         Author:TJ is too short

Json Formatter

I'm trying to use SweetAlert2 but I'm having issues to display error messages when something goes wrong. Also, when the user presses the "Cancel" button, the console displays the error: Uncaught (in promise) cancel.

In short, there is a button on my website. If the user presses that button a confirm dialog appears (using SweetAlert2). Here is my code:

swal({
    title: "Are you sure?",
    text: "You will not be able to undo this action!",
    type: "warning",
    showCancelButton: true,
    cancelButtonText: 'No, cancel!',
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, do it!",
    allowOutsideClick: false
    preConfirm: function () {
        return axios.put('/api/endpoint')
        .then(response => {
            console.log('success')
        })
        .catch(error => {
            console.log('failure')
            swal({
                title: "Something went wrong",
                type: "error",
            })
        });
    }
}).then(function (result) {
    if (result.value) {
        swal('Deleted!', 'Your file has been deleted.', 'success')
    } else if (result.dismiss === 'cancel') {
        swal('Cancelled', 'Your file is safe :)', 'error')
    }
});

If something goes wrong, will be nice to display another SweetAlert2 dialog saying "Something went wrong", but instead of that, it looks like SweetAlert2 is somehow capturing the error and displaying it inside the same confirmation box. Also, there is the issue with the cancel button: If the user cancels, the console displays the already mentioned error.

SweetAlert2 uses promises and I'm still learning how to use them properly, so maybe there is something that I'm doing in the wrong way.

Any help, please?

Thanks in advance

Author:TJ is too short,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47369371/sweetalert2-and-promises
yy