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:
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:This is in the helper. Once you have that, you can do something like this: