0

I'd like to read some information from an remote CSV file using a callback function. Not sure, how exactly to do this.

function:

function getRoomsFromCSV(allRoomsArray) {
  var request = require('request');
  request('http://localhost:3333/rooms.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
...
      allRoomsText = allRoomsText.substr(0,allRoomsText.length-1) + ']}';
      var allRoomsArray = JSON.parse(allRoomsText);
  }
 })
}

I'd like to call the function and loop through the result array.

 var rooms = [];
 getRoomsFromCSV( function (rooms) {
   for(var i = 0; i < rooms.length; i++) {
      console.log("i:",i);
  }

However, the for loop is never called and the result (room) seems to be empty.

1
  • You are re declaring var allRoomsArray Commented Jan 16, 2017 at 11:37

1 Answer 1

1

Try like this

function getRoomsFromCSV(allRoomsArray) {
  var request = require('request');
  request('http://localhost:3333/rooms.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
...
      allRoomsText = allRoomsText.substr(0,allRoomsText.length-1) + ']}';
      allRoomsArray(JSON.parse(allRoomsText)); //response params to callback
  }
 })
}

You sent callback to retrieve response. so call that callback inside the async function

Sign up to request clarification or add additional context in comments.

1 Comment

thx, that was it! However, rooms.length is undefined, although it has a value when I watch the rooms variable in the debugger

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.