1

My app is an SMS lightning component, so in many situations, I'm doing DML updates AND making a callout. I have avoided the "uncommitted work pending" errors by using @future (callout=true) on all the callout methods. Works great.

Now, I'm doing a bulk SMS feature using Batch Apex to access tens of thousands of records to pull the phonenumber and making a single callout. Batch apex won't allow future methods, so I'm using global class QueueWave implements Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts { as recommended by @AmitChaudhary here.

That seems to work for getting around the @future prohibition, however, I also need to update each of the records that have been accessed (logging the fact that they have been included in the blast), and I think I need to do it in the execute() method of the Batch class (there could be too many to do all at once in the finish() method).

My problem is now that my callout is not in a future method, I'm getting the uncommitted work pending error because I'm calling out and trying to do DML.

Any suggestions on how to handle this?

1 Answer 1

3

The fundamental problem with this error is one of ordering: you cannot perform a callout after DML, because the system is then stuck holding your database transaction open while it waits for the callout to complete. Hence, the simplest solution is to perform all DML operations after the callouts. Then, you don't need any extra asynchrony at all.

Otherwise: You cannot call @future methods in Batch Apex context, but the restriction is rather lighter on Queueable Apex: the limit on Queueable jobs in a batch transaction is 2.

If each execute() invocation processes a number of records that can be updated safely in a single transaction, deferring the DML into a Queueable job (where you may pass sObjects to its constructor, in contrast to primitive-only @future methods) could be an ideal solution.

2
  • Ah, thanks. I'll swap the order and confirm back here that it works. Jul 10, 2019 at 1:55
  • Yep, that did the trick. Thanks David! Jul 10, 2019 at 2:03

You must log in to answer this question.

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