[SalesForce] How to get return value from helper class to controller class

I want to have the value of Helper class's function who calls Apex method and return the state to controller from where it is being called?

For eg. below is the code :

DummyController.js
    callHelper : function(component,event,helper){
        var isSuccess = helper.createRecord (component,'dum1');
        console.log(isSuccess);
    }

DummyHelper.js
    createRecord : function (component,recordName){
       var action = component.get('c.apexCreateRecord'); // calls an apex method
       action.setParams({
           'name' : recordName
       });
       action.setCallback(this, function(response) {
         var state = response.getState();
         return state; // Want this state value to above controller's variable isSuccess. 
       });
       $A.enqueueAction(action);
    }

Is this possible or is there any other way to achieve this? Currently when I debug this in console it calls console.log line before helper's function response.
Thanks.

Best Answer

In Aura, you can use a Promise to wait for the result. That would look like this:

callHelper: function(component,event,helper){
    helper.createRecord(component,'dum1')
    .then(function(result) {
       console.log(result);
    });
}

  createRecord: function(component, recordName) {
    return new Promise(
      $A.getCallback(function(resolve, reject) {
        var action = component.get("c.apexCreateRecord"); // calls an apex method
        action.setParams({
          name: recordName
        });
        action.setCallback(this, function(response) {
          var state = response.getState();
          resolve(state);
        });
        $A.enqueueAction(action);
      })
    );
  }

Notice how it looks almost identical, except that you wrap everything up in a return new Promise($A.getCallback(function(resolve, reject) {...})) design. You can actually codify this in to a helper method that you can use everywhere. That looks like this:

server: function(component, actionName, params) {
    return new Promise($A.getCallback((resolve, reject) => {
        var action = component.get(actionName);
        params && action.setParams(params);
        action.setCallback(this, result => {
            switch (result.getState()) {
                case "DRAFT":
                case "SUCCESS":
                    resolve(result.getReturnValue());
                    break;
                default:
                    reject(result.getError());
            }
        });
        $A.enqueueAction(action);
    }));
},

This is in the helper. Once you have that, you can do something like this:

callHelper: function(component, event, helper) {
  helper.server(component, 'c.apexCreateRecord', { name: 'dum1' })
    .then(result => { /* deal with result */ })
    .catch(error => { /* there was an error, deal with it */ });
}
Related Topic