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

Check the below video first if you are planning to use Continuation

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 :


Posted

in

by

Comments

24 responses to “Continuation object in Apex – Asynchronous callouts for long running request – Live Demo”

  1. VK Avatar
    VK

    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. dmachop Avatar
    dmachop

    How do you do with multiple request and responses?

  3. Sanchit Dua Avatar
    Sanchit Dua

    What are the governor limits mitigated by the use of Continuation object?

    1. Jitendra Zaa Avatar

      Hey Sanchit,
      It will allow you to escape the limit of ten concurrent long-running callouts, where ‘long-running’ means ‘more than five seconds’.

      1. Sanchit Dua Avatar
        Sanchit Dua

        Thanks!

  4. Ron Nelson Avatar
    Ron Nelson

    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. Jitendra Zaa Avatar

      You should be able to do it. You can try a small example to execute this on page load.

      1. Sachin Avatar
        Sachin

        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!

        1. Jitendra Zaa Avatar

          Instead of page load, can you try using action function & call it after page load using JS.

  5. Jonas Fernandez Avatar
    Jonas Fernandez

    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. Rodolfo Carvalho Avatar
      Rodolfo Carvalho

      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.

  6. Shivani Avatar
    Shivani

    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.

  7. Karthi S Avatar
    Karthi S

    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

  8. MK2007 Avatar
    MK2007

    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.

    1. Jitendra Zaa Avatar

      Can you please share sample code to reproduce the problem ?

  9. Manav Avatar
    Manav

    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 .

    1. Jitendra Zaa Avatar

      Hey Manav, For chained continuation, you would need to write test classes separately for each call. This is official Salesforce documentation on how to write test class – https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_continuation_testing.htm

  10. Rajendra Singh Avatar
    Rajendra Singh

    “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.

  11. sundarayya Avatar
    sundarayya

    can you please provide the test class for this kind of methods using Continuation methods

  12. Vineet Goel Avatar
    Vineet Goel

    How can I initiate Continuation through Apex instead of Vf page. Let’s say I want to initiate RequestService from another method, can we do that??

  13. Eduardo Hurtado Avatar
    Eduardo Hurtado

    Hi, if you use a WSDL object response and not HTTPResponse, how do you do? Thanks!

  14. Karan Darawade Avatar
    Karan Darawade

    How can we transfer state to callback method?Also can we call continuation method from trigger?

  15. Salesforce_Guy Avatar
    Salesforce_Guy

    Will we be able overcome callout time limit exception from this approach? If the callout is taking more then 2 mins to process.

  16. Neha Avatar
    Neha

    Hi, I am hitting a limit in one of my implementation: requestformkeyslimitexceeded , which generelly come when we implement continuation with vf pages. So max # of keys in http post form should be 500.
    Can you please advice if you happen to see this error anytime and how to approach for this. It the page which needs redesign or its http request which is exceeding some size limits?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.