Huan Ho
Huan Ho

Reputation: 145

Resolving Promises Asynchronously in angularjs

My code:

$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);
});

Expect:
I want to add value to mail.Files finish,then call apiService.post()

Actual:
But it execute apiService.post() with mail.Files value is [].
When apiService.post() execute finish mail.Files return value.length > 0.

Upvotes: 0

Views: 46

Answers (3)

C.Champagne
C.Champagne

Reputation: 5489

Without knowing exactly which library you are actually using, it seems clear to me that fileUploadService.uploadImage() is asynchronous.

The function that you give as an argument is a callback and there is no guarantee that it would be executed "on time". In your case the path is added to imageUploadResults after the moment where you set $scope.mail.Files.

you should set $scope.mail.Files and call resolve in your callback function.

$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);
});

Upvotes: 2

atn
atn

Reputation: 904

When you assigned $scope.mail.Files = imageUploadResults; and resolved resolve($scope.mail); there are no guarantee that fileUploadService.uploadImage finished request and saved imageUploadResults.push(result.LocalFilePath);

Possible solution is to add resolve($scope.mail); right after imageUploadResults.push(result.LocalFilePath); in function passed to fileUploadService.uploadImage

Upvotes: 1

Jeffrey Jarry
Jeffrey Jarry

Reputation: 156

Your .then function should be using $scope.mail and not mail as a parameter? so as of right now you're sending an empty object through instead of the mail object.

Upvotes: -1

Related Questions