Continuation Apex in LWC
In this blog post, we will look at how to invoke an Apex method using Continuation.
In this blog post, we will look at how to invoke an Apex method using Continuation.
The reason behind using Continuation is when we want to make time-consuming actions (like making a callout to an external platform etc ) we will be going with this option.
Let's look at the sample code (please check the comments in the code )!
public with sharing class ContinuationController {
//Endpoint to which we will be making the callout
private static final String LONG_RUNNING_SERVICE_URL = 'XX';
//continuation and cacheale should be true!
@AuraEnabled(continuation=true cacheable=true)
public static Object startRequest() {
//Instantiate the Continaution class
//Also, pass the timeout when instantiation
Continuation con = new Continuation(40);
//this is the callback method
con.continuationMethod='processResponse';
//Data that you want to pass to the callback method
con.state='Hello, World!';
//Create the request
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(LONG_RUNNING_SERVICE_URL);
//add the request to continuation instance
//we can add upto 3 requests
con.addHttpRequest(req);
//pass the continuation instance to the framework
return con;
}
// Callback method
@AuraEnabled(cacheable=true)
public static Object processResponse(List<String> labels, Object state) {
System.debug(' 🚀 ' +state);
//labels[0] is the response of the first request
HttpResponse response = Continuation.getResponse(labels[0]);
String result = response.getBody();
System.debug(' 🚀 ' +result);
return result;
}
}
SampleContinuationClass.cls This is the Controller of the Web Component that invoke the apex method.
import { LightningElement, wire } from "lwc";
import startRequest from "@salesforce/apexContinuation/ContinuationController.startRequest";
export default class ContinuationComponent extends LightningElement {
@wire(startRequest)
records({ data, error }) {
console.log(data);
console.log(error);
}
}
continuationController.js Hope this was helpful!