GET request with axios returning undefined

2020-07-24 05:34发布

问题:

I'm trying to perform a get request using the following:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  var data: Order[]
  axios.get('http://localhost:8082/marketUpdates')
  .then(function (response) {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  

  console.log("Data before sending is ")
  console.log(data);
  response.send(data);
}))

However, my console.log near the bottom gets executed before the console.log in .then.

data is undefined when it is being sent. Does anyone know how I can avoid this?

回答1:

  1. The code is async, so all code below the request is getting executed while the request is waiting for the response. You can just move logs from bottom avoe the axios.get
  2. Your data inside then is not the same data as you're sending... You are using function(response) instead of arrow func. (response) => {} so you're binding another this.

Try it this way:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  let data: Order[]
  console.log("Data before sending is ")
  console.log(data);
  axios.get('http://localhost:8082/marketUpdates')
  .then((getResponse) => {
    console.log("GET Response")
    console.log(getResponse.data);
    data = getResponse.data;
    response.send(data);
  })
  .catch(function (error) {
    console.log("Error while fetching market updates");
  });  
}))


回答2:

Requests sent to a server are always asynchronous. That means, that the function .then() will be executed when the server responded.

Let me reformat your code:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");

  var data: Order[];

  console.log("Data before sending is ")
  console.log(data);

  axios.get('http://localhost:8082/marketUpdates')
  .then((response) => {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;

    response.send(data);
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  
}))

With the line axios.get('http://localhost:8082/marketUpdates') you are triggering a request to the server, who will respond, but this takes time. JavaScript will not stop it's execution of the function to keep the user interface running while the program is waiting for the server to respond.

So .get returns a Promise, that holds several function that get invoked in different scenarios. The function that is given as first parameter to .then will be invoked as soon as the server returned 200 and a response.

That means that your logs at the bottom of the code will be executed as soon as axios triggers the call to the server. At this point there is no data, because the server hasn't reacted yet.