function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anil DuttAnil Dutt 

You have uncommitted work pending. Please commit or rollback before calling out

Hi,

 I m in a situation where i need to insert Opportunity first then make a callout to do some operation. I created a Custom Button and Execute Javascript on its click.

Here is my Apex class

 global class CreditMemo {
    Webservice static string CloneOpp(string oppId)
    {
      string message = '';
      try  
    {
        List<Opportunity> listOpp = new List<Opportunity>();
       Opportunity oppOld = [SELECT Name FROM Opportunity WHERE Id = :oppId];
      Opportunity oppNew    = oppOld.clone(false, false);
      oppNew.Name = 'CLONED - ' + oppOld.Name;
          insert oppNew;

  HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          req.setEndpoint('http://test.com/salesforce/TransactionFromCreditMemo?oppid='+oppID);
          req.setMethod('GET');
          res = http.send(req);
          string result = res.getBody();
}
}

Above method return foloowing error : You have uncommitted work pending. Please commit or rollback before calling out

Then i use Future Method

@future (callout =true)
      public static void HttpResult(String oppID) {
          HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          req.setEndpoint('http://test.com/salesforce/TransactionFromCreditMemo?oppid='+oppID);
          req.setMethod('GET');
        try
          {
              res = http.send(req);
              string result = res.getBody();
              Opportunity opp = [SELECT ID,AmMessage__c FROM Opportunity WHERE Id = :oppID];
        opp.AmMessage__c = result;
             Database.update(opp);
         }
}

But as we can not return message from Future method, i try to update a filed in Opportunity to get message but found that Future Method is Asyncronus , getting data from Opportunity after calling Future Method does not get updated data.

I need to call Callout after Opportunity insert only as i needed new Id in Callout function and also need to get message from Webrequest.

Please suggest how can i achieve this

Thanks