Passing result from one helper function to another

helperlightninglightning-aura-components

I am trying to get the org domain in a lightning comp and use that to redirect to the QLE of a record. For some reason, I am receiving undefined on my helper fucntion that calls a nother helper function, which gets the org domain from the apex controller. Can someone point why I am getting this issue? Here are snippets of my code.

//Apex Controller

@AuraEnabled   
    public static string getDomain(){   
        String url = String.valueof(System.URL.getSalesforceBaseURL().gethost());
        String url2 = urlInstance.removeEndIgnoreCase('.my.salesforce.com');
        return url2;
    }

//Helper.Js

fetchDom: function(component, event, helper, result) {

    var orgDom = component.get("c.getDomain");
    console.log('orgDom: ', orgDom ); **//THIS IS GETTING RESULT**

    orgDom.setCallback(this, function(response) {
        var result = response.getReturnValue();
        console.log('result: ' +  result);
        return result;
    });
},
rediRectToUrl: function (component, event, helper, result) {
    let recordId = result;
    var myDomain = this.fetchDom(component, event, helper, result);
    console.log('myDom:', myDom); **//THIS IS GETTING UNDEFINED**

    var urlEvent = $A.get("e.force:navigateToURL");
    urlEvent.setParams({
      "url": 'https://' + myDomain + '--sbqq.visualforce.com/apex/sb?scontrolCaching=1&id=' + recordId + '#quote/le?qId=' + recordId
    });
    urlEvent.fire();
}

Best Answer

You didn't call $A.enqueueAction, so the server was never called. In addition, server calls are asynchronous, so you need to wait for the result. We do this with a Promise. In addition, you called the variable myDom at one point, and myDomain at the other.

  fetchDom(component) {
    return new Promise((resolve, reject) => {
      const orgDom = component.get('c.getDomain')
      orgDom.setCallback(this, function (response) {
        const status = response.getState()
        if (status === 'SUCCESS') {
          resolve(response.getReturnValue())
        }
        if (status === 'ERROR') {
          reject(response.getError())
        }
      })
      $A.enqueueAction(orgDom)
    })
  },
  rediRectToUrl(component, event, helper, result) {
    const recordId = result
    this.fetchDom(component).then((myDomain) => {
      console.log('myDomain:', myDomain)
      const urlEvent = $A.get('e.force:navigateToURL')
      urlEvent.setParams({
        url: `https://${myDomain}--sbqq.visualforce.com/apex/sb?scontrolCaching=1&id=${recordId}#quote/le?qId=${recordId}`,
      })
      urlEvent.fire()
    })
  }
Related Topic