0

I am using Promise JS in my lightning component to make a server call. The apex class makes a callout to a external endpoint and returns the response to the component. This is working fine. After reading this blog - 'https://www.sitepoint.com/overview-javascript-promises/' I thought that we can handle future callout in this Promise object context but it is not working. Just wanted to understand if this could be possible to handle any future callout in Promise JS. Or we just need an listener service to handle the response back from the future callout like we do normally.

LC: `

<div class="slds-m-around--medium">
    <!--Header part-->

    <div class="slds-page-header" role="banner">
        <div class="slds-media__body">
            <p class="slds-page-header__title slds-truncate" title="foreign exchange rates">foreign exchange rates By HTTP Callouts</p>
            <lightning:button variant="brand" label="Make CallOut" onclick="{! c.calloutCtrl }" />             
        </div>
    </div>
    <!--Header part close-->
    <h3 class="slds-section-title--divider"> Base : {!v.response.base}</h3>
    <h3 class="slds-section-title--divider"> Date : {!v.response.date}</h3>
    <h3 class="slds-section-title--divider"> Converted USD : {!v.convertedUSD}</h3>
    <!--iterate the list of Currency-->    
</div>

`

Controller:

({
    calloutCtrl : function(component, event, helper) {
var errorHandler = $A.getCallback(
            function(error)
            {
                alert('Error: ' + error[0].message);
            });

        var symbols = 'USD';
        //helper.getResponse(component, base);
        var methodPromise = helper.executeAction(component, 'getresonsefromServer', { 'url' : 'http://data.fixer.io/api/latest?access_key=1b705f6a7b712da42b5b5f849af5ad44&symbols='+symbols });
        methodPromise.then($A.getCallback(function(result){
            component.set("v.response", result);
        }),errorHandler).then($A.getCallback(function(result){
            console.log('Inside second method chain');
            component.set("v.convertedUSD",component.get("v.response.rates.USD"));
        }));        
    }
})

Helper:

({
    executeAction : function(component,methodName,parameters) {
        return new Promise(function(resolve,reject){

            var actionRequest = component.get('c.' + methodName);
            if(parameters)
            {
                actionRequest.setParams(parameters);
            }

            actionRequest.setCallback(this, function(response)
            {
                if(component.isValid() && response.getState() === 'SUCCESS')
                {
                    console.log('returned from server:::'+JSON.stringify(response.getReturnValue()));
                    resolve(response.getReturnValue());
                }
                else
                {
                    reject(response.getError());
                }
            });
            $A.enqueueAction(actionRequest);
        });
    }
})

Controller class:

public with sharing class InvokingClassFromLightning {
    public InvokingClassFromLightning() {

    }
    @AuraEnabled
    public static Map<string,Object> getresonsefromServer(string url)
    {
        CalloutToCurrencyConversion.calloutresponsecontent(url);
        return CalloutToCurrencyConversion.map_value;
    }
}

Callout class:

public with sharing class CalloutToCurrencyConversion {
    public static ResponseWrapper callout_resp{get;set;}
    public static Map<string,Object> map_value{get;set;}
    @future(callout=true)
    public static void calloutresponsecontent(string url)
    {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');

        HttpResponse resp = h.send(req);
        system.debug('Response body'+resp.getBody());
        //callout_resp = (ResponseWrapper)JSON.deserialize(resp.getBody(), ResponseWrapper.class);
        map_value = (Map < String, Object > ) JSON.deserializeUntyped(resp.getBody());

    }
}
4
  • Could you please add the code you've tried and be more specific about what "not working' means?
    – David Reed
    Commented Oct 14, 2018 at 12:24
  • also what do you mean by future callout here? Are you talking about @future method or any asynchronous operation performed from JS?
    – Mr.Frodo
    Commented Oct 14, 2018 at 12:27
  • Yes I mean to say @future method. Commented Oct 14, 2018 at 12:28
  • How @future is anyhow related with the JS? Future methods are only related to Apex code.
    – Mr.Frodo
    Commented Oct 14, 2018 at 12:29

1 Answer 1

3

Promise object in javascript is used to basically perform any asynchronous operation in more synchronous fashion. Now suppose if you want to perform any HTTP callout or any other asynchronous operation whose result will return in some time future, to handle that result and perform any operation on that result Promise object is used.

Now if we talk about @future method, they are completely apex side part, they do not return anything. Their return type is always set to void.

Queueable Apex is the way to chain the async jobs into queue so that they execute one after another means in more sync fashion.

But promise API doesn't have anything to do here because that is for JS and @future is completely server side.

It is not clear why you are using @future in your code to perform callout when you can simply make callouts from @auraenabled methods as well, that would even return the result.

2
  • That means if we are making any asynchronous callout using XMLHttpRequest from controller then promise JS can be used to handle that response.correct? Commented Oct 14, 2018 at 12:43
  • I never tried that but as it is completely JS( In client side JS controller ) then i think promise can be used to handle the response.
    – Mr.Frodo
    Commented Oct 14, 2018 at 12:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .