在angularjs中异步解析Promise

时间:2016-08-29 14:58:18

标签: angularjs angular-promise

我的代码:

$q(function (resolve) {
    var imageUploadResults = [];
    fileUploadService.uploadImage($scope.filesUpload, "/api/mailbox/uploadAttachFile", function (result) {
        console.log(result);
        imageUploadResults.push(result.LocalFilePath);
    });
    $scope.mail.Files = imageUploadResults;
    resolve($scope.mail);
}).then(function (mail) {
    console.log(mail);
    apiService.post("/api/mailbox/sendMail", mail, sendMailSucceed, sendMailFailed);
});

期望值:
我想为 mail.Files 完成增值,然后调用 apiService.post()

实际
但它使用 mail执行 apiService.post()。文件值为[]。
apiService.post()执行完成 mail.Files 时返回value.length> 0.

3 个答案:

答案 0 :(得分:2)

在不确切知道您实际使用的库的情况下,我似乎很清楚fileUploadService.uploadImage()是异步的。

您作为参数提供的函数是回调函数,并且无法保证它将“按时”执行。在您的情况下,在您设置imageUploadResults之后,路径会添加到$scope.mail.Files

您应该设置$scope.mail.Files并在回调函数中调用resolve

$q(function (resolve) {
    var imageUploadResults = [];
    fileUploadService.uploadImage($scope.filesUpload, "/api/mailbox/uploadAttachFile", function (result) {
        console.log(result);
        imageUploadResults.push(result.LocalFilePath);
        $scope.mail.Files = imageUploadResults;
        resolve($scope.mail);
    });
}).then(function (mail) {
    console.log(mail);
    apiService.post("/api/mailbox/sendMail", mail, sendMailSucceed, sendMailFailed);
});

答案 1 :(得分:1)

当您指定var string ='"long one","short","oh, look","wow.", ""', array = JSON.parse('[' + string + ']'); console.log(array);并已解决$scope.mail.Files = imageUploadResults;时,无法保证resolve($scope.mail);已完成请求并已保存fileUploadService.uploadImage

可能的解决方案是在传递给imageUploadResults.push(result.LocalFilePath);的函数resolve($scope.mail);之后立即添加imageUploadResults.push(result.LocalFilePath);

答案 2 :(得分:-1)

您的.then函数应该使用$ scope.mail而不是邮件作为参数?现在,您正在通过而不是邮件对象发送空对象。