簡體   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