0

I have a future method that is called in trigger to create some records, and after that i use the records created in the future method to associate them with other entity.

Since future methods are asynchronous, when the code comes to the part of association, the record of future method are not created yet, and i got an error.

I can't move the association code to the future method because it's used in other classes, and i can't remove the @future annotation because it's used to avoid Mixed DML Operation error.

How can i solve this problem to assure that the association is executed when the future method has finished?

This is sample code of what i'm trying to do:

public class MyTriggerHandler {
    // Some logic
    ...

    // Call of future Method
    MyUtilClass.callFutureMethod();

    // some logic
    ...

    // Query records created in Future Method
    List<MyObject__c> myList = new List<MyObject__c>([select Id,... from MyObject__c where ...]);   // I have the error in this line

    // Asociate object in my list with Other entity
    ...
}
0

2 Answers 2

8

There is no choice here but to move the "association code" to a method that you call from the end of the future method and the other classes:

public class MyUtilClass {

    @future
    public static void callFutureMethod() {
        ...
        associationCode(...);
    }

    // Call this from the other classes
    public static void associationCode(...) {
        ...
    }
}

Asynchronous Apex usually runs quite quickly but can be delayed for minutes or hours and having a way to wait for it to complete would pretty much undermine its purpose of allowing transactions to complete in a short amount of time.

2
  • Presumably, there would be some state to pass to assocationCode.
    – Adrian Larson
    Aug 23, 2017 at 20:29
  • @AdrianLarson Added ... to represent that.
    – Keith C
    Aug 24, 2017 at 6:52
0

Another reason to use future methods instead of queueable is when your functionality is sometimes executed synchronously, and sometimes asynchronously. It’s much easier to refactor a method in this manner than converting to a queueable class. This is handy when you discover that part of your existing code needs to be moved to async execution. You can simply create a similar future method that wraps your synchronous method like so:

@future static void myFutureMethod(List params) { // call synchronous method mySyncMethod(params); }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .