Function not returning the value as anticipated

After receiving a CSV file from a URL, I am converting each row into an array of objects.

const translation = {
    '緯度': 'latitude',
    '経度': 'longitude',
    '測定局コード': 'Measuring station code',
    '測定局名称': 'Bureau name',
    '所在地': 'location',
    '測定局種別': 'Measuring station type',
    '問い合わせ先': 'Contact information',
    '都道府県コード': 'Prefecture code'
}
const csv_url = 'https://soramame.env.go.jp/data/map/kyokuNoudo/2022/10/06/01.csv';

// requesting the CSV file from csv_url and creating an array of station objects

var stations = [];
request(csv_url, (err, res, body) => {
    if (err || res.statusCode !== 200) {
        console.log(err);
    }
    else {
        const rows = body.split('\n');
        const headers = rows[0].split(',');
        for (let i = 1; i < rows.length; i++) { // starting at 1 to skip headers
            let station = {}; // creating a new station object for each row
            const row = rows[i].split(','); // splitting the row into columns
            for (let j = 0; j < row.length; j++) { // iterating through each column
                station[translation[headers[j]]] = row[j]; // adding the value to the station object using the header as the key
            }
            var data = stations.push(station)
            console.log(stations)
            return data;
        }
    }
}
);

Everything works fine... when I console.log(stations) inside the function, the expected output is displayed.

{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田2-12',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}
{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田2-12',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}
{
  latitude: '43.123333',
  longitude: '141.245000',
  'Measuring station code': '01107030',
  'Bureau name': '手稲',
  location: '札幌市手稲区前田2-12',
  'Measuring station type': '一般局',
  'Contact information': '札幌市',
  'Prefecture code': '01'
}

However, when I console.log(stations) outside of the function, an empty list is returned. I have declared 'stations' outside of the function, and the function is supposed to append the objects to the array. Why isn't it working as expected and how can this be resolved? Additionally, returning 'data' does not return the array from 'stations' either.

Answer №1

When you make the call to request, remember that it's asynchronous. Therefore, if you try to log stations right after calling request, you'll end up printing an empty list because the request is still running in the background. It happens too fast - before the stations list gets populated.

If you need to perform any actions with the stations data, you should either handle it within a success callback passed to request or use await for the request to complete.

As mentioned by Dai above, using push actually changes the content of the stations array.

If your request function returns a value, you could try something like

const response = await request(...)
(along with fixing the issue Dai highlighted - one solution could involve moving the declaration of stations inside the else block and returning stations at the end of the else block).

If you cannot use await, then you will have to pass a callback that handles the addition of new elements to the stations array as it is currently defined.

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

Ensure you click the Google captcha v3 button two times in order to successfully carry out the action

I recently integrated recaptcha v3 into a form and encountered an issue where the submit button had to be clicked twice to function correctly. Upon the first click, the captcha validation is triggered. After the second click, the form will successfully red ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Fixing memory leaks in C++ caused by dynamic arrays using Valgrind

After numerous attempts to resolve this issue, I am still struggling to find a solution. Valgrind has highlighted a memory leak in my resize method, and it seems like there might be a simple oversight on my part. The .h file private: int* pArray; / ...

Error: 'fs' module not found in React.js and cannot be resolved

Encountering issues with tatum io v1 + react? Developers have acknowledged that it's a react problem which will be addressed in V2. In the meantime, you can utilize tatum io V1 with node js. I've included all dependencies that could potentially ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

What is the best way to make sure that only one tab changes color when clicked?

I have been working on a function that changes the color of a tab to gold when clicked, which is working fine. However, I also want to toggle the active property of each tab so that it displays a nice white outline. The problem I'm facing is that the ...

What could be causing the second image to not drop in the proper position in an HTML and JavaScript environment?

I am encountering an issue with a simple drag and drop implementation using images in my code. The first image works fine, but for some reason the second image does not display correctly when dragged inside the div boxes; it appears outside of the box. Can ...

Having trouble getting my Blender model to render accurately in three.js

Currently, I am attempting to create a basic gear animation for my website using three.js. Initially, I crafted a gear mesh in Blender with a splendid, shiny bronze material, and exported it to three.js json format using the blender exporter and the code p ...

Determine if there is any item in a collection that includes a specified attribute found in a separate set

I've attempted various solutions for this issue and have searched around but I'm unable to get it to work. I am dealing with 2 arrays and need to verify if any of the items in one array contain any of the strings from the other array. const ste ...

Unexpected display of Unicode text retrieved through ajax requests

In my setup, I have both an admin module and a front end module available. Specifically, there is a category section that plays a key role in the functionality. To create categories, I utilize AJAX to send data from a text box to PHP. It's important ...

Is quick searching suitable for a sluggish processor?

I'm working on creating an index for a large document to enable word searching (sometimes referred to as concordances). Currently, the process takes approximately 10 minutes as I go through each paragraph to compile a list of unique words along with t ...

What is the best way to perform this task in Angular2?

I am currently working with three arrays: tables = [{number:1},{number:2},{number:3},{number:4}]; foods = [ {id:1, name:'Ice Cream'}, {id:2, name:'Pizza'}, {id:1, name:'Hot Dog'}, {id:2, name:'Salad'} ]; o ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...

When importing a component that is passed as a prop in React, it is causing a blank page to render and is displaying an error in the

Visit this link for the code Everything was running smoothly with the app until I decided to include the Icon component in SidebarOption.js. Now, upon doing so, a blank page appears and an error is displayed in the console: An error occurred stating that ...

JS: Ensuring Cross-Browser Compatibility - my JavaScript code functions correctly in Chrome but experiences issues in Firefox

I am facing an issue with my JavaScript code that works perfectly in Chrome but not in Firefox. I lack the experience to troubleshoot this problem on my own and would appreciate some assistance. I tested the code both locally on my development machine usi ...

The object for checking Ajax connections is not providing any values

I've been working on creating a unique AJAX connection check object, but unfortunately I'm struggling to get it to function properly. :/ Here's the object structure: function Connection(data){ this.isConnected = false, this.check = funct ...

Tips for chaining actions in Javascript using ActionSequence, LegacyActionSequence, or a similar method

I encountered an error while attempting to execute this example, despite trying both ActionSequence and LegacyActionSequence. I am in search of the correct method to chain actions. My attempts to find a solution in resources such as https://seleniumhq.git ...

unable to render the JavaScript code

Utilizing JavaScript post an ajax request to showcase the data in a div using new JS content. The example code is provided below: //ajax call from a.jsp var goUrl = "/testMethod/getTestMethod; var httpRequest=null; var refreshCont ...