Work with a Continuation in an Apex Class
To work with a continuation in an Apex class, use the Apex Continuation
object.
Before you can call an external service, you must add the remote site to a list of authorized remote sites in the Salesforce user interface. From Setup, in the Quick Find box, enter Remote Site Settings
. Select Remote Site Settings, and then click New Remote Site. Add the callout URL corresponding to LONG_RUNNING_SERVICE_URL
in the Apex Class Continuation example below.
If the callout specifies a named credential as the endpoint, you don’t need to configure remote site settings. A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. In your code, specify the named credential URL instead of the long-running service URL.
-
To make a long-running callout, define an Apex method that returns a
Continuation
object. (Don’t worry about the attributes of the@AuraEnabled
annotation yet. We explain that soon.) -
Set an Apex callback method to be invoked after the callout completes in the
continuationMethod
property of theContinuation
object. In this example, the callback method isprocessResponse
. The callback method must be in the same Apex class. -
Set the endpoint for a callout by adding an
HttpRequest
object to theContinuation
object. A singleContinuation
object can contain a maximum of three callouts. Each callout must have a remote site or named credential defined in Setup. -
Set data to pass to the callback method in the
state
property of theContinuation
object. Thestate
property has anObject
type so you can pass in any data type that’s supported in Apex. -
Code the logic in the Apex callback. When all the callouts set in the
Continuation
object have completed, the Apex callback method,processResponse
, is invoked. The callback method has two parameters that you can access.labels
—A list of labels, one for each request in the continuation. These labels are automatically created.state
—The state that you set in thestate
property in yourContinuation
object.
-
Get the response for each request in the continuation. For example:
-
Return the results to the component’s JavaScript file.
Here’s a complete Apex class that ties together all the earlier steps.