JavaScript-链接承诺不会按顺序运行

时间:2019-07-15 21:36:09

标签: javascript promise

我正在开发一个小型应用程序,用户可以通过一个公共输入文件字段上传多个文件。

当用户单击“提交”按钮时,我正在运行以下代码:

function UploadFiles() {
    var loadFiles = document.getElementById('selectedFile').files;
    for (var i=0; i<=loadFiles.length;i++){
        var fileOgg = loadFiles[i];
        if (fileOgg!=undefined || fileOgg!=null){

            new Promise(function (resolve, reject) { resolve (fileOgg); })
            .then(UploadFilesStep)
            .then(retrieveMetadata)
            .then(changeMetadata)
            .then(moveTo)
            .then(showSuccess); 
        }
    }    
}

这是UploadFilesStep的详细信息:

var UploadFilesStep = function (fileOgg) {
    return new Promise(function(resolve, reject) {
        pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
        // This is a SharePoint PnP call to file upload
        pnp.sp.web.getFolderByServerRelativeUrl("/sites/mysite/Config").files.add(fileOgg.name, fileOgg, true).then(function(result) {
            console.log("FileUpload success");
            resolve([result, fileOgg]);
        });   
    })
}

retrieveMetadata代码:

var retrieveMetadata = function ([result, fileOgg]) {
    return new Promise(function(resolve, reject) {
        pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
        result.file.listItemAllFields.get().then(function(listItemAllFields) {
            resolve([listItemAllFields, fileOgg]);
        });
    })
}

这是changeMetadata的承诺:

var changeMetadata = function ([listItemAllFields, fileOgg]) {
    return new Promise(function(resolve, reject) {
        pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
        pnp.sp.web.lists.getByTitle("Config").items.getById(listItemAllFields.Id).update({
            Number: ""+number+"",
        }).then(function(r){
            console.log("Properties updated successfully! Go to MoveTo");
            resolve(fileOgg);
        });
    })
}

最后是MoveTo代码:

var moveTo = function (fileOgg) {
    return new Promise(function(resolve, reject) {
        var nameFile = fileOgg.name;
        var timestamp = + new Date();
        var fileName = nameFile.substr(0, nameFile.lastIndexOf('.'));
        var newFileName = fileName + "-" + timestamp;
        var sourceFileUrl = _spPageContextInfo.webServerRelativeUrl+"/Config/"+nameFile+"";
        var targetFileUrl = _spPageContextInfo.webServerRelativeUrl+"/Attachments/"+nameFile.replace(fileName, newFileName)+"";
        var headers = headers || {};
        var method = 'POST';
        headers["Accept"] = "application/json;odata=verbose";
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
        var endpointUrl = siteurl2 + "/_api/web/GetFileByServerRelativeUrl('" + sourceFileUrl + "')/MoveTo(newurl='" + targetFileUrl + "',flags=1)";
        var payload;

        $.ajax({
            url: endpointUrl,
            type: method,
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(payload),
            cache: false,
            headers: headers,
            async: false,
            success: function (data) {
                strResults += "";
                counterUpload = counterUpload + 1;
                resolve();
            },
            error: function (data) {
                strResults += "Error " + JSON.stringify(data, null, 4);;
                resolve();
            }
        });
    }); 
}

从浏览器的控制台中,我可以看到前两个诺言(UploadFilesStepretrieveMetadata)以正确的顺序运行。 然后,我看不到changeMetadata日志,但是似乎在UploadFiles中使用for循环。 过了一会儿,我收到来自changeMetadata的响应,它通常返回404错误(“链接到pnp js文件的“在使HttpClient请求变为可查询状态时出错”)。

我在做什么错了?

0 个答案:

没有答案