简体   繁体   中英

variable not available after for-loop inside Promise.then()

I'm using a for-loop containing an if statement inside of a Promise.then() (it's an api call). A variable initialized before the for-loop is available within the for-loop, but not after.

I've console.logged the variable before the for-loop, just inside the for-loop, inside the if statement, after the if statement, and after the for-loop. That last console.log doesn't even come up undefined. It just doesn't seem to register at all.

I've tried simple versions of the same basic structure in the Chrome console and it works, but the difference is that in the Chrome console I'm not within a Promise.then(). So I think there's something I'm not understanding about it.

$(document).ready(function() {
  const url = 'https://www.ndbc.noaa.gov/data/realtime2/46029.spec';
  const newBouyData = new BouyData();

  let currentBouyData = newBouyData.getBouyData(url);
  currentBouyData.then((text) => {
    const today = new Date();
    let lineDate;
    let line;
    let lineArray;
    const lines = text.split('\n');
    let currentData;

    for (let i = 2; i <= lines.length; i++) {
      line = lines[i];
      lineArray = line.split(' ');
      lineDate = new Date(lineArray[0], lineArray[1] - 1, lineArray[2]).toLocaleDateString();

      if ( today.toLocaleDateString() === lineDate && today.getHours() === parseInt(lineArray[3]) ) {
        currentData = lineArray;
      }
    }
    console.log('currentData after: ', currentData);
. . .

I'm expecting currentData to be an array of strings. I'm getting nothing. Not even a console.log.

What am I missing?

Thanks for your thoughts.

for (let i = 2; i <= lines.length; i++) {
  line = lines[i];
  lineArray = line.split(' ');
  ...
}
console.log('currentData after: ', currentData);

The valid indices of an array arr are from 0 to arr.length - 1 .

Your loop condition is i <= lines.length , meaning in the last iteration i has a value of lines.length . lines[i] then accesses an element outside of the array bounds, yielding undefined .

lineArray = line.split(' ') then throws an exception because undefined is not an object and undefined.split is an error.

That's why the code after the loop is never executed.

Try i < lines.length .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM