Continuation object in Apex – Asynchronous callouts for long running request – Live Demo

We may run into scenario in Salesforce project, where we need call external web service but no need to wait for response. Response from external web service can be processed asynchronously and once processed it can be presented in Visualforce page.

We can accomplish this by using Actionsupport or Javascript remoting. However, this is possible with using Continuation method as well.  In Continuation approach, we can call external web service and inform that which callback method should be used to  process response. After execution of callback method, data is presented in visualforce page.

Execution Flow of an Asynchronous Callout - Image from Salesforce documentation
Execution Flow of an Asynchronous Callout – Image from Salesforce documentation

Below code demonstrate complete usage of this.

Apex code

/**
* 	@Author	:	Jitendra Zaa
 * 	@Web	:	https://jitendrazaa.com
 *
 * */
public class ISOtoCodeService {
    public String countryISO {get;set;}
    public String response {get;set;} 

	private String baseSericeURL = 'http://services.groupkt.com/country/get/iso2code/';
    private String returnedContinuationId ;

    public ISOtoCodeService()
    {
        countryISO = 'IN';
    } 

    public Object requestService(){

        //Timeout in seconds, 60 is limit
        Continuation con = new Continuation(60);

        // Set callback method
        con.continuationMethod='renderResponse';

        // Create callout request
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint(baseSericeURL+countryISO);

        returnedContinuationId = con.addHttpRequest(req);

        return con;
    }

    public Object renderResponse() {
      // Get the response by using the unique label
      HttpResponse httpRes = Continuation.getResponse(returnedContinuationId);
      // Set the result variable that is displayed on the Visualforce page
      response = httpRes.getBody();
      // Return null to re-render the original Visualforce page
      return null;
    }

}

Visualforce code

<apex:page tabStyle="Opportunity" controller="ISOtoCodeService" docType="html-5.0" sidebar="false" showHeader="false" showChat="false">
    <apex:form >
        <apex:pageBlock title="Continuation Demo">
            Country ISO :
            <apex:input label="Country ISO" value="{!countryISO}"/>
            <apex:commandButton action="{!requestService}" value="Request Service" reRender="responseBlock"/>

        </apex:pageBlock>

        <apex:pageBlock title="Response from Webservice" id="responseBlock">

<pre> {!response} </pre>

        </apex:pageBlock>
    </apex:form>
<style type="text/css">
        pre{
         	font-size : 1.7em;
        }
    </style>

</apex:page>

Make sure to add URL “http://services.groupkt.com” in remote site settings.

Live Demo :

Related posts

19 thoughts on “Continuation object in Apex – Asynchronous callouts for long running request – Live Demo”

  1. Hello I cannot see the Live demo. I have tried I.E, Chrome and Firefox. In I.E it said that the content needs to be opened in another window or tab but when I did it is taking me to SF login screen. With Chrome and Firefox, it is just blank frame. Trying to load the frame in another tab/window does not do anything. Please help.

  2. I’m working on a use case where I want this to be executed on page load. I’m attempting to re-work the existing web service call into an asynchronous call. Can this be done in much the same way?

      1. I also have a similar use case. Any success with it?

        I’m calling a method from action attribute of
        From that method I’m calling the continuation method.
        For some reason, But the call back method is not getting invoked.

        Any help/pointers would be highly appreciated.
        Thanks!

  3. I tried to use your code for testing but whenever I tried to request service, I’m getting an array “Return type of an Apex action method must be a PageReference. Found: core.apexpages.el.adapters.ApexObjectValueELAdapter”. should I change the return type to PageReference instead of Object?

    1. It happened to me as well, and I’ve just figured it out. Make sure your Visual Force page AND Apex class API versions are at least 30. Mine was 27 and it wasn’t working.

  4. Hi ,

    Can you provide some sample or direct towards any doc if it needs to make more than one async calls? For example – login, getSomeData, logout.

  5. Hi, We make callout from a batch job and we get timeout exceptions. At times this request will have been succeeded and If we retrigger the callout from salesforce it might create a duplicate record in the external system.

    Is there a way to handle this within salesforce.

    Thanks
    Karthikeyan

  6. I am using a visual force custom component on a visual force page. VF page has it’s own controller and the custom component has it’s own. Custom component is making call outs synchronously and I need to make it asynchronous using Continuation so that the main page rendering is not held back due to call-out in custom component. However I find that when using Continuation the call-out request is not even made. There is no error shown in the log.I just see 0 call-outs in the log. Anyone has attempted this before? I searched for a while but did not find any case which has custom component and Continuation both are used.

    Any suggestions are welcome.

  7. I am implementing chained continuation for calling 3 api one after other . I am not getting any sample Test class code for testing chained continuation .

  8. “We can accomplish this by using Actionsupport”, Sir I think actionsupport make synchronous calls to page controller? If i am wrong? Please let me know.

Leave a Reply