2

I am using Async XMLHttpRequest to make an API call. Here's the workflow of my program,

first_function(){
var valueToBeReturned = 0;

 makeRequest(myCallback)//function for API call

 /*rest of the code*/
 console.log("print second");
 return valueToBeReturned;
}

function makeRequest(callback){
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "my_url", true);
    xhttp.send(null);
    xhttp.onload = function() {
        if(xhttp.readyState === 4) {
            if(xhttp.status === 200) {
                response = JSON.parse(xhttp.responseText);
                callback(null, response);
            }
        }
    }
}

function myCallback(data){
    console.log("print first")
}

Now what happens is every time I run it, the entire code in the first function is executed and then the code in makeRequest is executed. I understand JS is synchronous in nature and everything. But I'm not able to get my work done here, which is fisrt it makes API call, then callback is executed, then the code after makeRequest. What am I doing wrong here?

PS this is not the actual code, just to demonstrate the flow of my program

5
  • makeRequest(){} — you forgot the function keyword and the callback parameter. JS is asynchronous in nature. Commented Apr 4, 2018 at 5:50
  • I'll edit my question. This is not the actual code, but just to demonstrate the workflow. I've written the same in the actual code @Xufox Commented Apr 4, 2018 at 5:51
  • 1
    So you have already working code for the myCallback callback. Put the code to be executed after the request in the callback. Commented Apr 4, 2018 at 5:53
  • You are probablly getting print second printed first before the print first, which is not unexpected. That is how Async XMLHTTPRequest works. Commented Apr 4, 2018 at 6:18
  • Instead of returning the value valueToBeReturned I suggest you returning a promise. Read more about AJAX at developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started Commented Apr 4, 2018 at 6:29

1 Answer 1

1

You need to put callback as a parameter in makeRequest. I'm not sure what that null is there for, though. If you want "print second" to print second, you'll need to execute it after myCallback - maybe insert another callback?

function first_function(){
  var valueToBeReturned = 0;
  makeRequest(myCallback, restOfTheCode)
  function restOfTheCode() {
    /*rest of the code*/
    console.log("print second");
  }
}

function makeRequest(callback1, callback2){
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "my_url", true);
  xhttp.send(null);
  xhttp.onload = function() {
    if(xhttp.readyState === 4 && xhttp.status === 200) {
      const response = JSON.parse(xhttp.responseText);
      callback1(response);
      callback2(response);
    }
  }
}

function myCallback(data){
  console.log("print first");
}

But this whole thing would be a whole lot nicer if you used Fetch and Promises instead:

function makeRequest() {
  return fetch('my_url')
    .then(response => response.JSON())
}
// consume the request:
makeRequest()
  .then(responseJSON => {
     // do stuff with the responseJSON
   });
Sign up to request clarification or add additional context in comments.

1 Comment

thnx both worked as expected. Also the null parameter indicates that no body content is needed for the GET request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.