Apex Class

Apex Future Methods in Salesforce

Apex Future methods let the developers perform asynchronous tasks, such as long-running operations and external callouts, without hindering user experience. In this article, we will explore how to implement Future Apex Methods, their capabilities, limitations, return types, and parameters they can receive.

Illustrative representation about Apex Future Methods

Implementing an Apex Future Method

To begin, create a static method in your Apex class and annotate it with the @future annotation. The @future annotation indicates that the method will run asynchronously at a later time, freeing up the main thread to perform other tasks.

public class MyFutureApexClass {
    @future
    public static void performAsyncTask(String param1, Integer param2) {
        // Your asynchronous logic here
    }
}

Calling the Future Method

Now that you have defined the Future Apex Method, you can call it from other synchronous Apex methods or triggers. The data passed to the method will be processed asynchronously, ensuring it doesn't impact the user's experience.

public class MyCallingClass {
    public void executeTask() {
        String data1 = 'Sample Data';
        Integer data2 = 42;
        MyFutureApexClass.performAsyncTask(data1, data2);
        // The method will be executed asynchronously, allowing the main thread to continue.
    }
}

What does the callout true?

The callout=true attribute is a crucial aspect of Future Apex Methods, as it enables developers to perform callouts to external web services. By default, Apex doesn't allow synchronous callouts from within asynchronous methods. However, by adding "callout=true" to the "@future" annotation, Salesforce grants permission for such callouts, expanding the capabilities of Future Apex Methods.

@future(callout=true)
public static void performAsyncCallout(String param) {
    // Perform the external callout here
}

@future annotation: Their Limitations

Future Annotation in Salesforce comes with some limitations that you need to be aware before start coding:

Testing Future Apex Methods

Testing Future Apex Methods is similar to testing other asynchronous Apex methods. To test a Future Apex Method, call the method within a Test.startTest() and Test.stopTest() block. This will ensure that the method is executed synchronously, allowing you to add assertions to validate the expected behavior of the asynchronous method.

@isTest
public class TestMyFutureApexClass {
    
    @isTest
    static void testFutureMethod() {
        Test.startTest();
        MyFutureApexClass.performAsyncTask('Test Data', 100);
        Test.stopTest();

        // Add your assertions here to validate the expected behavior of the asynchronous method.
    }
}