How to wait until user response on confirmation dialog and then preventDefault (unselection)?

I want to use e.preventDefault(); to prevent the deselection of an option by the user only if user responds No to a confirmation dialog. The confirmation dialog opens only if the result of an ajax call is true.

What I have tried so far is to create a function that makes the ajax call and returns the promise.
> function ajaxCall(action, url, data){

            var def = $.ajax({...
            def.done(function(result){...
            def.fail(...
            return def.promise();
        }

Using the same pattern, I created a function to wait for the user input.
function displayConfirmationDeg() {
var dialogComp=$(’

’);
var defer = $.Deferred();
    dialogComp.dialog(
        {
            autoOpen: false,
            resizable: false,
            modal: true,
            title: "title",           
            close: function() {             
            },          
            buttons: [{ html: "<i class='ace-icon fa fa-check bigger-110'></i>Yes", "class" : "btn btn-info btn-xs",
                click: function() { 
                    defer.resolve("true");  
                    $(this).dialog("close");                    
                }
               },
               { html: "<i class='ace-icon fa fa-times bigger-110'></i>No", "class" : "btn btn-xs btn-reset",
                    click: function() {
                        defer.resolve("false");
                        $( this ).dialog( "close" );
                    }
               }] 
        }
    ).html("<div class='alert alert-info bigger-110 no-margin-bottom align-center'> Message here </div>");  
    if (dialogComp.dialog("isOpen")===true){return false;}   
    dialogComp.dialog('open');

    return defer.promise();
}

And finally chain those two in the following.

$(’.’+currentSelect.attr(‘id’)).on(‘select2:unselecting’, function (e) {
$
.when(ajaxCall(‘POST’, ‘/url/’,…)
.then(function(result){
if(result){
$
.when(displayConfirmationDeg())
.then(function(answer){
if(answer==‘false’){
e.preventDefault();
}
})
}
})
})

However when the user deselects an option, the option is removed before the confirmation dialog opens.
Also to make sure that this logic is executed before the deselection, I am using the “.on(‘select2:unselecting’”, yet it doesn’t work as expected.

The then() callback from your Promise runs asynchronously, which means your event handler will have exited before your then() callback runs. Since you’re calling e.preventDefault() in your callback, it will be called too late to prevent the select2:unselecting event.

I believe you can make jQuery AJAX calls synchronously. That’s what you need to do inside your event handler. (Alternatively, if you’re running your app on supporting browsers, you can use async/await to do the same thing.)