Angular - 一系列承诺 - 我做错了什么?

时间:2015-01-11 20:32:05

标签: angularjs promise

我有一些服务将文件上传到我的服务器,然后我的服务器转换文件。我使用这样的服务:

uploadService.uploadFileWaitForConversion(fileToUpload).then(
    function(fileid) {
        console.log("Upload success");
        console.log(fileid);
    },
    function(error) {
        console.log("error uploading");
    );
);

服务代码:

// Checks the progress of the conversion.  Success means it's done.  409 means it's still converting
function checkFileStatus(uuid, attempts) {
    return $http.get('/api/upload/' + uuid, {
    }).then(
        function (response) {
            console.log("File been converted and file uuid returned");
            return response.data;
        },
        function (error) {  // API returns 409 if it's still being processed
            console.log(attempts);
            if (error.status === 409) {
                attempts--;
                if (attempts > 0) {
                    $timeout(function () {
                        checkFileStatus(uuid, attempts)
                    }, 2000);
                } else {
                }
            }
        }
    );
}

function uploadFileWaitForConversion(fileToUpload) {
    return $upload.upload({
        url: '/api/upload',
        file: fileToUpload
    }).then(
        function (response) {
            var fileID = response.data.file;
            console.log("File uploaded, now let's convert");
            return checkFileStatus(fileID, 5).then(
                function() {
                    console.log("Conversion done!");
                    return fileID;
                },
                function() {
                    return 0;
                }
            );
        },
        function (error) {
            return 0;
        }
    );
}

我希望打印出来:

  • 文件已上传,现在让我们转换
  • 5
  • 4
  • 3 //现在完成转换
  • 文件已转换,文件uuid已返回
  • 转换已完成
  • 上传成功

相反,这会打印:

  • 文件已上传,现在让我们转换
  • 5
  • 转换已完成
  • 上传成功
  • 4
  • 3 //完成转换

0 个答案:

没有答案