Skip to content Skip to sidebar Skip to footer

How To Use Confirm Alert And Return An Ajax Promise?

I have an existing function that returns an AJAX promise. I want to update this function to display a confirmation alert before running the AJAX call, but other parts of the code u

Solution 1:

You could use jQuery's Deferreds ?

functiondoTheDeed() {
    var def = $.Deferred();

    bootbox.confirm('Are you sure?', def.resolve);

    return def.promise().then(function(result) {
        return result ? $.post('/api/delete/123') : "no go";
    });
}

doTheDeed().done(function (data) { 
    if (data == 'no go') {
        // user declined
    } else {
        // item deleted
    }
}).fail(function(err) {
    // something failed
});

Solution 2:

Building on Adeneo's answer, and adhering to the principle of promisifying at the lowest level, bootbox could be monkeypatched with a reusable promisification of bootbox.confirm(), without having to hack into bootbox itself.

If you do this then it will be appropriate :

  • to allow the challenge text and noGo message to be specified by the caller.
  • to send the noGo condition down the error path.
if(!bootbox.confirmAsync) {
    bootbox.confirmAsync = function (challenge, noGoMessage) {
        challenge = challenge || 'Are you sure?';
        noGoMessage = noGoMessage || 'User declined';
        return jQuery.Deferred(function (def) {
            bootbox.confirm(challenge, function (confirmed) {
                confirmed ? def.resolve() : def.reject(newError(noGoMessage));
            });
        }).promise();
    }
}

doTheDeed() would then comprise a totally conventional then chain starting with bootbox.confirmAsync(...), for example :

functiondoTheDeed () {
    return bootbox.confirmAsync('Are you sure you want to delete?', 'User declined to delete')
    .then(function (data) {
        return $.post('/api/delete/123');
    })
    .then(null, function (err) {
        // if user declined, then 'User declined to delete' will come back as err.messageconsole.log(err.message);
        return err; // jQuery v<3.0// throw err; // jQuery v>=3.0
    });
}

Post a Comment for "How To Use Confirm Alert And Return An Ajax Promise?"