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
Scott0987Scott0987 

Wait for an http request to complete before moving on in @future method

I hope this isn't a dumb question but I am still fairly new to apex.  I have an http callout in an @ future method.  Is there a way to wait for the response before moving on with the rest of the code?  Here is my code if that helps.

@future

HttpRequest req = new HttpRequest();
        req.setEndpoint('http://..... endpoint here);
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
        //I want it to wait here for the response before moving on.
        while (parser.nextToken() != null) {
        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){
                String fieldName = parser.getText();
                parser.nextToken();
                if(fieldname == 'id') {
                    IDset.add(parser.getText());
                }
            }
        }

 

Best Answer chosen by Admin (Salesforce Developers) 
Scott0987Scott0987

I found a way to do what I want for anyone else who needs this.  I put the rest of my code into a different method that was not set with the @future call.  Here is the code:

    public static void parseresults(string s){

    }
    
    @future(callout=true)
    public static void runUpdate(){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://..... endpoint here');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        class.parseresults(res.getBody());
    }

 

All Answers

Jeff MayJeff May

I think the very nature of @future means this will not wait.   If you want to wait for a return, you can just make an HttpRequest and process its return inline.

Scott0987Scott0987

I found a way to do what I want for anyone else who needs this.  I put the rest of my code into a different method that was not set with the @future call.  Here is the code:

    public static void parseresults(string s){

    }
    
    @future(callout=true)
    public static void runUpdate(){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://..... endpoint here');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        class.parseresults(res.getBody());
    }

 

This was selected as the best answer