繁体   English   中英

使用promises同步执行ajax

[英]Using promises to execute ajax synchronously

这是我处理文件上传的代码:

但是因为我没有使用promises,所以它没有以正确的顺序运行! 当我上传多个文件时,代码的ajax部分在最后运行(我正在使用krajee bootstrap并且此代码执行实际的文件上传!)。 这是代码:

$('#uploadNoteImage').on('fileloaded', function (event, file, previewId, index, reader) {
    var url = noTrailingSlash(window.location.href) + '/user/notes';
    console.log("1) Notes upload number: "+index);

    var imgpgno = parseInt(getNotesLength(noteTitle, notesData));
    console.log("2) Got page number of image "+imgpgno);

    var data = {
        "subject": noteTitle,
        "pgno": imgpgno + 1,
        "note": reader.result
    };

    console.log("3) Formed data object:");
    console.log(data);
    $.ajax({
        url: url,
        method: "PUT",
        data: data,
        success: function (data) {
            console.log("4) Successfully uploaded data");
            console.log(data);
            toastr.success('', 'Added!');
            var order = getIndexToDelete(noteTitle, notesData);
            console.log("5) Fetched order number: "+order);
            var id = Math.floor(Math.random() * 1000);
            if (imgpgno == 0) {
                console.log("6)(No notes uploaded yet state) Images before uploading"+images);
                modalImg.src = reader.result;
                notesData[order].data.push({
                    "id": id, "pgno": imgpgno + 1,
                    "note": reader.result
                });
                images = imgpgno + 1;
                console.log("7)(No notes uploaded yet state) Images after uploading: "+images);
                // imgpgno++;

            }
            else if(imgpgno!=0) {
                var newPageNo=imgpgno + 1;
                console.log("6)(1 note uploaded state) Pushing data with pgno: "+newPageNo);
                notesData[order].data.push({
                    "id": id, "pgno": newPageNo,
                    "note": reader.result
                });
                images = imgpgno + 1;
                console.log("7)(1 note uploaded state) Images after uploading: "+images);
            }
        },
        error: function (err) {
            toastr.error('Try again!', 'Something went wrong in uploading note!');
            console.log(err);
        }
    });
});

我如何在这里包含promises,以便代码以正确的顺序运行? 我在这里详细概述了这个问题: AJAX代码的延迟执行

最简单的方法需要一点点“设置” -

var uploadInProgress = $.when();

这将“填充” uploadInProgress变量,以便第一次上传将在我们希望的时候开始

整个代码与您已有的代码差别不大:

var uploadInProgress = $.when();
$('#uploadNoteImage').on('fileloaded', function (event, file, previewId, index, reader) {
    // here, we chain the "pending" upload to this one
    uploadInProgress = uploadInProgress.then(function() {
        var url = noTrailingSlash(window.location.href) + '/user/notes';
        console.log("1) Notes upload number: "+index);

        var imgpgno = parseInt(getNotesLength(noteTitle, notesData));
        console.log("2) Got page number of image "+imgpgno);

        var data = {
            "subject": noteTitle,
            "pgno": imgpgno + 1,
            "note": reader.result
        };

        console.log("3) Formed data object:");
        console.log(data);
        return $.ajax({
            url: url,
            method: "PUT",
            data: data
        // since we are using Promise pattern, use .then for success, and .catch for error conditions
        }).then(function (data) {
            console.log("4) Successfully uploaded data");
            console.log(data);
            toastr.success('', 'Added!');
            var order = getIndexToDelete(noteTitle, notesData);
            console.log("5) Fetched order number: "+order);
            var id = Math.floor(Math.random() * 1000);
            if (imgpgno == 0) {
                console.log("6)(No notes uploaded yet state) Images before uploading"+images);
                modalImg.src = reader.result;
                notesData[order].data.push({
                    "id": id, "pgno": imgpgno + 1,
                    "note": reader.result
                });
                images = imgpgno + 1;
                console.log("7)(No notes uploaded yet state) Images after uploading: "+images);
                // imgpgno++;

            }
            else { // if(imgpgno!=0) { // the check is redundant since when the above if condition is false, this has to be true
                var newPageNo=imgpgno + 1;
                console.log("6)(1 note uploaded state) Pushing data with pgno: "+newPageNo);
                notesData[order].data.push({
                    "id": id, "pgno": newPageNo,
                    "note": reader.result
                });
                images = imgpgno + 1;
                console.log("7)(1 note uploaded state) Images after uploading: "+images);
            }
        }).catch(function (err) {
            // this catch ensures that the next upload will be able to run regardless of this upload's failure
            toastr.error('Try again!', 'Something went wrong in uploading note!');
            console.log(err);
        });
    });
});

取而代之的是的success: / error:回调,使用的事实, $.ajax返回一个Promise ,和使用.then / .catch -这使得它很容易链上传后,其他请求一个

注意:确保.catch实际上处理错误(即不抛出一个)或者promise链将破坏 - 你error:的代码error:很好,因为它是

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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