0

I'm building a website using Airtable API to scrape data from an Airtable spreadsheet using JS.

I'm running into a fairly simple(?) problem using JavaScript.

I'm putting data from the spreadsheet into a string array names. console.log(names[0]) prints out the string value correctly, but when I try to do something like:

var test = names[0];

console.log(test),

It prints out undefined


Why does this happen?


My Code:

var names = [];
var locations = [];

//ACCESS AIRTABLE API (GET DATA FROM AIRTABLE SPREADSHEET)
var Airtable = require('airtable');
var base = new Airtable({apiKey: 'keyQ7YUX3SUECVL4C'}).base('appSmUKDnFdEAT1YF');

base('Members').select({
  view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
    //Fill arrays with data from spreadsheet
  records.forEach(function(record) {
        names.push(record.get('parsedName'));
        locations.push(record.get('parsedLocation'));
  });
  fetchNextPage();

}, function done(err) {
    if (err) { console.error(err); return; }
});
ChaosNova
  • 11
  • 3
  • That would suggest that `names` has not been loaded at that point in time. – Taplar Apr 23 '20 at 22:41
  • 2
    Are you loading the array with an asynchronous function? If so, see https://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron – Barmar Apr 23 '20 at 22:41
  • @Barmar yes it seems so. Read a little bit about async, promises, callbacks, etc..., but still not really sure how to fix the problem. – ChaosNova Apr 23 '20 at 23:09
  • The basic idea is that everything that needs to use the result immediately after it's returned has to be in the callback function. In your case, put `console.log(names[0])` at the end of the `eachPage()` callback function. – Barmar Apr 23 '20 at 23:17
  • Right before `fetchNextPage()` – Barmar Apr 23 '20 at 23:17

0 Answers0