The axios GET request failed to return a defined value

My current issue involves making a get request using the following code snippet:

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, I am facing a problem where my final console.log statement at the bottom executes before the console.log within the .then block.

This leads to 'data' being undefined when it gets sent. Does anyone have any suggestions on how to resolve this timing issue?

Answer №1

  1. When working with asynchronous code, make sure to keep in mind that the execution continues while waiting for a response. To avoid issues, move any logs from below the request above the axios.get call.
  2. Ensure consistency in your data handling by using arrow functions instead of function expressions inside the `then` method. This will prevent inadvertently binding another `this`.

Consider restructuring your code like this:

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

Answer №2

When requests are sent to a server, they are always asynchronous. This means that the function .then() will only be executed once the server has responded.

Allow me to reformat your code for better clarity:

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

By including the line

axios.get('http://localhost:8082/marketUpdates')
, you are initiating a request to the server. However, this process takes time as the server needs to respond. JavaScript does not pause its execution while waiting for the server response to ensure smooth running of the user interface.

Therefore, the .get method returns a Promise containing various functions that are invoked under specific circumstances. The function provided as the first parameter to .then will be called once the server responds with a status code of 200 and a valid response.

As a result, the logs at the end of your code snippet will be executed immediately after axios sends the request to the server. At this point, there won't be any data available since the server has yet to provide a response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an If statement tailored for a particular image source: a step-by-step guide

In the program I am running in Dreamweaver, there is a specific line of code that looks like this: function go() { if((document.test.test1.src == document.test.test2.src && document.test.test2.src == document.test.test3.src )) ...... ...... ..... ...

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

Conceal user input field in React using a hook

I am looking for assistance with a form that has 4 input fields: username, password, email, and mobile. My goal is for the email field to disappear if an '@' symbol is typed in the username field, and for the mobile field to disappear if any digi ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

Tips for creating a linear movement effect for a collection of objects

I am working on animating a linear gripping motion for picking and placing objects. Here is a codesandbox link where you can see the issue I am facing: https://i.sstatic.net/dUdPv.png The gripper is created, moves down to reach the LEGO brick, and then s ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be w ...

How can I remove threads in Python?

I am new to Python, but I am trying to set up a simple UDP socket server with asynchronous connections. Although I have limited experience with Python, I have heard great things about the language and decided to use it for this project. Following the exam ...

How does the Express next() function trigger the execution of the following middleware?

Can someone please explain how the next() function is able to call the subsequent middleware or route? I've searched everywhere but can't seem to find a good resource with the actual code. If anyone could share where I may find this information, ...

Achieving the incorporation of multiple components within a parent component using Angular 6

Within parent.component.html The HTML code I have implemented is as follows: <button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button> <app-addresse *ngFor="let addres of collOfAdd" [add]="addres">< ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Swap references between two components at the same level

There are two instances of custom-component spawned by a shared parent with distinct data, each displayed as a tab in the mat-tab-group. <mat-tab-group> <mat-tab label="TAB1"> <ng-template matTabContent> <custom-componen ...

Error: Unable to locate namespace 'google' in TypeScript

I am currently working on an angular-cli project. ~root~/src/typings.json { "globalDevDependencies": { "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459", "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", "sele ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...

Unable to persist data while submitting a form on Django framework

I am currently working on a Django tutorial to create a small website where users can add pages and categories. I have defined a Page model as shown below: class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ...

Why does my JavaScript only trigger my web service request when I set a breakpoint?

Can you help me understand why my JavaScript code only calls my webservice when I set a breakpoint on the line ].getJSON, but not if I remove the breakpoint? $(function () { $("#" + @Model.BidObjectId).submit(function () { ale ...

In React, a singular reference cannot establish focus amidst an array of references

Scenario In this scenario, we are restricted to using only keyboard navigation without any mouse clicks. Imagine a situation where we have 10 table rows displayed on the screen. Each row contains a menu button for interaction. When the tab key is pressed ...

How can I effectively test a method within a React component using Jest and Typescript?

When working on .tsx components using Typescript and React, I want to write unit tests for the methods within my React component. For example: export default class SomeComponent extends React.Component<undefined, SomeComponentState> { someMetho ...

Troubleshoot: Unable to utilize mapActions with Vuex modules

Having trouble using mapActions to reference actions in my modules. The Vuex docs say that module actions are not namespaced by default, so they should be accessible like main store actions. Here's how I have things set up: Store import * as ModuleA ...

Vue alert: Component resolution failed while attempting to create a global component

I am new to Vue Typescript and I have been encountering an issue while trying to create global components. I received a warning and the component did not load on the template. Here is how I attempted to create global components: App.vue import { createApp ...