1

So, I've heard that you cannot do any Callouts after a DML operation in Apex. So, I've designed my app this way (some pseudo-code follows):

String url;
List<Object> chunk;

for (Integer page=1; page<10; page++) {

    url = '/responses?per_page=' + PER_PAGE + '&page=' + page;

    // Callout happens inside client.get():
    chunk = (List<Object>)JSON.deserializeUntyped(client.get(url));

    // all DML is in here
    ProcessRecordsJob processJob = new ProcessRecordsJob(chunk);
    System.enqueueJob(processJob);
}

From what I know, a queued job must have an isolated execution context. So, why do I get "Uncommitted work pending"?

Note: it's not in the test (there is not real isolation in tests, but that's different issue); it works this way on the prod…

Note 2: I can see in the logs that the error happens after it tries to execute "page=2" (i.e. second) callout request.

Could the System.enqueueJob() itself produce that DML, after which I can't do no more callouts?

1 Answer 1

2

Yes, doing pretty much anything with the database will cause this exception to be thrown. This includes scheduling jobs, using queueable or batchable, sending emails, performing normal DML operations, and so on. You'll have to move the System.enqueueJob call outside the loop.

3
  • Ok, i've redesigned it a bit: public with sharing class SyncResponses implements Queueable, Database.AllowsCallouts { public void syncIt() { url = '/responses?page=' + this.page; .. some checks that next page is possible ..; System.enqueueJob(new SyncResponses(this.page+1); }} Now I get System.AsyncException: Maximum stack depth has been reached. when trying to test is… After the third page.
    – pilat
    Commented Nov 21, 2022 at 15:15
  • I mean, there's no loop now, just enqueuing the same class with the next page number in the arguments
    – pilat
    Commented Nov 21, 2022 at 15:17
  • 1
    @pilat That's a Developer/Sandbox limitation. In production, you wouldn't encounter that error.
    – sfdcfox
    Commented Nov 21, 2022 at 15:53

You must log in to answer this question.

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