Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  158] [ 3]  / answers: 1 / hits: 53170  / 7 Years ago, wed, january 10, 2018, 12:00:00

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?


More From » http

 Answers
26

  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);
});
}))

[#55490] Monday, January 8, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylee

Total Points: 60
Total Questions: 119
Total Answers: 101

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;