0

I have a cross platform app built using Monaca and AngularJS. The app uses the Camera plugin that allows users to take photos.

A have a function that takes the pictures, and in that function I want to return a few values when the photo is successfully captured.

Below is my method that calls the takePicture() function, along with trying to access the returned values. The 2 functions below are called from different Controllers/Services as well.

Controller

// Take photo
$scope.takePicture = function () {
    var test = Photo.takePicture();
    alert("photoCaptured: " + test.photoCaptured + "\nphotoName" + test.photoName); // Error here
};

Below is the takePicture() function that fires the Camera and returns the values at the onSuccess callback

Service

// Get the main app.js module
var photo = angular.module("photo", []);
photo.service("Photo", function () {
    var myFunctions = {
        // Take picture
        takePicture: function () {

            var onSuccess = function (imageURI) {
                var photoCaptured, photoName;
                return { photoCaptured: true, photoName: imageURI } // Should return multiple values
            }
            var onFail = function (error) {
                alert("AN ERROR HAS OCCURED" + "\nPhoto capture failed." + error);
            }

            var options = { quality: 50, destinationType: Camera.DestinationType.FILE_URI};
            navigator.camera.getPicture(onSuccess, onFail, options);
        },
    }
    return myFunctions;
});

However, the test throws error Cannot read property 'photoCaptured' of undefined.

How do I access the values returned from the onSuccess callback?

heyred
  • 2,031
  • 8
  • 44
  • 89
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 29 '17 at 16:09
  • See the duplicate question for your issue. By the way this code doesn't make sense `var photoCaptured, photoName; return { photoCaptured: true, photoName: imageURI }` you are going to create an object and those are properties names, not variables – quirimmo May 29 '17 at 17:59

2 Answers2

0

You're assigning test to the return value of Photo.takePicture(), so if that function does not return a value, test will remain undefined and trying to access any property of test will throw the error Cannot read property x of undefined.

shawon191
  • 1,945
  • 13
  • 28
0

As noted by Andreas - the answer at THIS duplicate question solved my issue. In my case $q.defer did the trick.

heyred
  • 2,031
  • 8
  • 44
  • 89