连接两个异步调用

时间:2016-08-09 12:16:24

标签: javascript jquery

以下JavaScript在SharePoint中将项目添加到列表,将文件添加到图片库。 add函数调用上传函数,但我不想在上传函数完成之前完成add函数。当然,上传功能大部分时间都需要更长的时间。这样做的最佳方式是什么?

将项目添加到列表中:

function addNewPunchlistItem() {

var endpointUrl = myURL + "PunchlistTracking/_api/web/lists/getbytitle('Punchlist Items')/items";

if ($('#getFile').val()) {
    uploadFile(myFormDigest, '#getFile', $('#itemNumber').val() + "_image.png");
}

call;

var call = $.ajax({
    url: endpointUrl,
    type: "POST",
    data: JSON.stringify({
        "__metadata": { type: "SP.Data.Punchlist_x0020_ItemsListItem" },
        Title: $('#itemShortDesc').val(),
        FSEId: $('#itemFSE').val(),
        PunchlistNumber: $('#itemNumber').val(),
        Open: $('#itemOpenDate').val(),
        Type: $('#itemType').val(),
        ResponsibleId: $('#itemResponsible').val(),
        LongDescription: $('#itemLongDesc').val(),
        ItemImage: { Description: "", Url: myURL + "PunchlistTracking/Lists/PicturesList/" + $('#itemNumber').val() + "_image.png" }
    }),
    headers: {
        Accept: "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-RequestDigest": myFormDigest
    }
});

call.done(function (data, textStatus, jqXHR) {
    alert('Punchlist item ' + $('#itemNumber').val() + " added successfully.");
    init();
});

call.fail(function (jqXHR, textStatus, errorThrown) {
    alert('fail');
    var response = JSON.parse(jqXHR.responseText);
    var message = response ? response.error.message.value : textStatus;
    console.log(message);
});
}

上传文件:

function uploadFile(FormDigest, FileInput, fileName) {

var serverRelativeUrlToFolder = 'Lists/Pictures';
var fileInput = jQuery(FileInput);

var serverUrl = myURL + "PunchlistTracking";

var getFile = getFileBuffer();

getFile.done(function (arrayBuffer) {

    var addFile = addFileToFolder(arrayBuffer);
    addFile.fail(onError);
});

getFile.fail(onError);

function getFileBuffer() {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(fileInput[0].files[0]);
    return deferred.promise();
}   //  getFileBuffer

function addFileToFolder(arrayBuffer) {

    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName);

    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": FormDigest,
            "content-length": arrayBuffer.byteLength
        }
    });
}   //  addFileToFolder

function onError(error) {
    alert(error.responseText);
}   //  onError

}   //  uploadFile

1 个答案:

答案 0 :(得分:0)

最好的方法是使用Promises,就像你已经在做的那样。获取 uploadFile 函数以返回承诺,然后在该承诺的“then”或“done”中进行第二次调用。正如您使用 getFileBuffer 调用和 addFileToFolder 调用一样