I have a future method where I make an external REST api call which gets kicked off in an after update trigger on the Opportunity object.

When the results come back, I deserialize the JSON and then make an update to the Opportunity object using one of the values that come back in the api call.

This seems to work most of the time, but a few times it seems that maybe my update call ran before the api results came in.

I gather this is happening because my update statement is running before the results from the API call are returned due to the nature of the future method?

Is there a way to always ensure the results from the API have been returned before I run my update statement?

Here is my code:

@future (callout=true)
public static void makeCallout(String jsonBody, String verbType, Id oppId) {
    String endpoint = 'callout:' + getEnvironmentSettings().get('rootAPIURL') + '/v1/cutomers?apikey=' + getEnvironmentSettings().get('apiKey');

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Type', 'application/json');
    HttpResponse res = h.send(req);

    Map<String, Object> workflowResults = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());

    Opportunity oppToUpdate = [SELECT Id, Workflow_ID__c FROM Opportunity WHERE Id = :oppId];

    oppToUpdate.Workflow_ID__c= (String) workflowResults.get('workflow_id');

    update oppToUpdate;

  • 1
    Please edit to show us the code you are using. – David Reed Nov 7 '19 at 22:58
  • 4
    No, that's not how Apex Code works (or the platform itself). You'll need to do debugging to figure it out, and if you want our help, you'll need to share your code in an edit. – sfdcfox Nov 7 '19 at 23:33

Your callout is performed synchronously. That is, Apex blocks until a response is received. (Incidentally, this is why you have to make the callout in a @future method and not from a trigger). The @future method as a whole is run asynchronously, but that doesn't affect the synchronous nature of the callout made within it.

There is no possibility that your update DML takes place prior to the return from the callout. The issue must lie elsewhere in your logic or integration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.