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?
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:
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.
then
is not the samedata
as you're sending... You are usingfunction(response)
instead of arrow func.(response) => {}
so you're binding another this.Try it this way: