在bootstrap-fileinput的filepredelete事件中,等待Sweetalert2异步确认后再继续。

3

我在使用Bootstrap文件上传插件和SweetAlert2遇到了一些问题。

这是为了显示一个对话框,以确认用户是否真的要删除该文件。

如果我要中止文件的删除,我需要在filepredelete事件中返回一个布尔值。该函数是同步的,但我正在使用一个带有promises的异步插件SweetAlert2。

这是我的代码:

$("#gallery-images").fileinput({
           ...

}).on("filepredelete", function(event, key, jqXHR, data) {

    swal({
        title: 'Are you sure you want to delete this image?',
        showCancelButton: true,
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning',
    }).then((result) => {
        if(result.value){
            return false;
        }
        return true;
    });

});

我找不到等待确认的方法。我考虑总是中止删除,当用户确认后手动删除文件。我需要重构我的代码。


你不能等待异步操作返回。我同意的唯一方法是“始终中止删除并在用户确认后手动删除文件”。 - Jacob Goh
1个回答

2

尝试使用Promises,我曾经为同样的问题苦苦挣扎了3天,最终找到了解决方法,希望能对其他人有所帮助。

$("#gallery-images").fileinput({
       ...

    }).on("filepredelete", function(event, key, jqXHR, data) {

    return new Promise(function(resolve, reject) {
            swal.fire({
                title: 'Are you sure?',
                text: 'You will not be able to recover this file!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, keep it'
            }).then((result) => {
                if (result.value) {
                    resolve();
                }
            });
        });

    });

享受吧!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接