使用promises同步执行ajax

时间:2017-06-25 07:17:59

标签: javascript jquery ajax twitter-bootstrap bootstrap-file-upload

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

但是因为我没有使用承诺,所以它没有以正确的顺序运行!当我上传多个文件时,代码的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,以便代码以正确的顺序运行?我在这里详细概述了这个问题:Late execution of AJAX code

1 个答案:

答案 0 :(得分:0)

最简单的方法需要一个小小的设置" -

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实际处理错误(即不会抛出错误)或承诺链将中断 - 您在error:中的代码是正常的