简体   繁体   English

在Promise.then()中的for循环后变量不可用

[英]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). 我在Promise.then()中使用包含if语句的for循环(它是一个api调用)。 A variable initialized before the for-loop is available within the for-loop, but not after. 在for循环之前初始化的变量在for循环中可用,但不在之后。

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. 我在for循环之前,在for循环内部,if语句内部,if语句之后,以及for循环之后控制记录变量。 That last console.log doesn't even come up undefined. 最后一个console.log甚至没有定义。 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(). 我在Chrome控制台中尝试了相同基本结构的简单版本,但它的工作原理不同,但不同之处在于Chrome控制台中我不在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. 我期待currentData是一个字符串数组。 I'm getting nothing. 我一无所获。 Not even a console.log. 甚至不是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 . 数组arr的有效索引是从0arr.length - 1

Your loop condition is i <= lines.length , meaning in the last iteration i has a value of lines.length . 你的循环条件是i <= lines.length ,这意味着在最后一次迭代中i的值为lines.length lines[i] then accesses an element outside of the array bounds, yielding undefined . 然后, lines[i]访问数组边界之外的元素,产生undefined

lineArray = line.split(' ') then throws an exception because undefined is not an object and undefined.split is an error. lineArray = line.split(' ')然后抛出异常,因为undefined不是对象而undefined.split是一个错误。

That's why the code after the loop is never executed. 这就是为什么循环之后的代码永远不会执行的原因。

Try i < lines.length . 试试i < lines.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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