Chrillewoodz
Chrillewoodz

Reputation: 28338

How to return a value to a controller from a function callback in a service via a promise

I'm putting together a simple email sender function (yes I know I shouldn't put it in my front end, this is just a test). The functionality works but I need to return a status message to my controller so I can display it on my page once the email has been sent/rejected.

I've been trying to get it to work for hours but my lack of proper knowledge working with callbacks/promises fails me so I need some guidance. How would I modify the code below so the controller can gain access to the status message?

core.service('email', ['$q', 'fetchContent', function($q, fetchContent) {

  return {
    sendEmail: function(info) {

      // Fetch token and recipient info from JSON file
      var getEmailInfo = fetchContent.getEmailInfo();

      getEmailInfo.then(function(res) {

        // Access the token and recipient from the JSON file we just requested
        var token = res.data.email.key,
            recipient = res.data.email.recipient;

        // Create a new mandrill instance and set the params
        var emailProvider = new mandrill.Mandrill(token),
            params = {
              "message": {
                "from_email": info.sender,
                "to":[
                  { "email": recipient }
                ],
                "subject": info.company,
                "text": info.message
              }
            };

        // Return a deferred promise containing our status message
        var deferred = $q.defer();

        emailProvider.messages.send(params, function(res) {
          deferred.resolve('Success message');

        }, function(err) {
          deferred.reject('Error message');
        })

        return deferred.promise;
      });
    }
  }
}]);

And then from my controller I want to receive the status message, either success or error, from the sendEmail function in my service:

$scope.send = function(data) {

  var validate = validation.validateEmail(data);

  validate.then(function(res) {

    if (res !== true) {
      $scope.error = res;
    }
    else {
      var status = email.sendEmail(data);
      console.log(status); // Always becomes undefined now
    }
  });
}

Upvotes: 1

Views: 868

Answers (1)

hussainb
hussainb

Reputation: 1296

In your service use the deferred.resolve() to call the success function in the .then() method in your controller.

Service

core.service('email', ['$q', 'fetchContent', function($q, fetchContent) {

  return {
    sendEmail: function(info) {

      // Fetch token and recipient info from JSON file
      var getEmailInfo = fetchContent.getEmailInfo();

      getEmailInfo.then(function(res) {

        // Access the token and recipient from the JSON file we just requested
        var token = res.data.email.key,
            recipient = res.data.email.recipient;

        // Create a new mandrill instance and set the params
        var emailProvider = new mandrill.Mandrill(token),
            params = {
              "message": {
                "from_email": info.sender,
                "to":[
                  { "email": recipient }
                ],
                "subject": info.company,
                "text": info.message
              }
            };

        // Return a deferred promise containing our status message
        var deferred = $q.defer();

        emailProvider.messages.send(params, function(res) {
            deferred.resolve('Success message');

        }, function(err) {
            deferred.reject('Error message');

        })

        return deferred.promise;
      });
    }
  }
}]);

Controller

$scope.send = function(data) {

  var validate = validation.validateEmail(data);

  validate.then(function(res) {

    if (res !== true) {
      $scope.error = res;
    }
    else {
      email.sendEmail(data).then(function(result){
        console.log(result);    // success message
      }, function(reason){
            console.log(result);    // error message
      });
    }
  });
}

Upvotes: 1

Related Questions