variable not available after for-loop inside Promise.then()Using global variables in a functionWhat is the scope of variables in JavaScript?How do I loop through or enumerate a JavaScript object?JavaScript closure inside loops – simple practical exampleHow to determine if variable is 'undefined' or 'null'?Loop through an array in JavaScriptCheck if a variable is a string in JavaScriptIs there a reason for C#'s reuse of the variable in a foreach?Loop inside React JSXWhy is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Reverse ColorFunction or ColorData

Why can’t you see at the start of the Big Bang?

How long did it take Captain Marvel to travel to Earth?

In "Avengers: Endgame", what does this name refer to?

What do you call a painting painted on a wall?

Does Thanos's ship land in the middle of the battlefield in "Avengers: Endgame"?

How important are good looking people in a novel/story?

What is monoid homomorphism exactly?

Explaining intravenous drug abuse to a small child

What is the thing used to help pouring liquids called?

Is the US ESTA (Electronic System for Travel Authorization) a visa?

Convert Numbers To Emoji Math

What word describes the sound of an instrument based on the shape of the waveform of its sound?

Can an Iranian citizen enter the USA on a Dutch passport?

How to say something covers all the view up to the horizon line?

Which "exotic salt" can lower water's freezing point by –70 °C?

Transistor gain, what if there is not enough current?

Where did Lovecraft write about Carcosa?

How do I, as a DM, handle a party that decides to set up an ambush in a dungeon?

Referring to person by surname, keep or omit "von"?

Primes in a Diamond

Why is the blank symbol not considered part of the input alphabet of a Turing machine?

Can a player choose to add detail and flavor to their character's spells and abilities?

My large rocket is still flipping over



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


Using global variables in a functionWhat is the scope of variables in JavaScript?How do I loop through or enumerate a JavaScript object?JavaScript closure inside loops – simple practical exampleHow to determine if variable is 'undefined' or 'null'?Loop through an array in JavaScriptCheck if a variable is a string in JavaScriptIs there a reason for C#'s reuse of the variable in a foreach?Loop inside React JSXWhy is my variable unaltered after I modify it inside of a function? - Asynchronous code reference






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















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.










share|improve this question






















  • Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

    – Khan Sharukh
    Mar 23 at 4:52






  • 1





    Add console.log inside for loop and debug it

    – varit05
    Mar 23 at 4:52











  • Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

    – Ray Toal
    Mar 23 at 4:58






  • 1





    you dont' care why no error in the console?

    – Jaromanda X
    Mar 23 at 5:28






  • 1





    @skillitzimberg - you probably have a .catch block in code you didn't show

    – Jaromanda X
    Mar 23 at 5:45

















1















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.










share|improve this question






















  • Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

    – Khan Sharukh
    Mar 23 at 4:52






  • 1





    Add console.log inside for loop and debug it

    – varit05
    Mar 23 at 4:52











  • Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

    – Ray Toal
    Mar 23 at 4:58






  • 1





    you dont' care why no error in the console?

    – Jaromanda X
    Mar 23 at 5:28






  • 1





    @skillitzimberg - you probably have a .catch block in code you didn't show

    – Jaromanda X
    Mar 23 at 5:45













1












1








1








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.










share|improve this question














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.







javascript for-loop asynchronous scope






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 4:47









skillit zimbergskillit zimberg

9426




9426












  • Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

    – Khan Sharukh
    Mar 23 at 4:52






  • 1





    Add console.log inside for loop and debug it

    – varit05
    Mar 23 at 4:52











  • Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

    – Ray Toal
    Mar 23 at 4:58






  • 1





    you dont' care why no error in the console?

    – Jaromanda X
    Mar 23 at 5:28






  • 1





    @skillitzimberg - you probably have a .catch block in code you didn't show

    – Jaromanda X
    Mar 23 at 5:45

















  • Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

    – Khan Sharukh
    Mar 23 at 4:52






  • 1





    Add console.log inside for loop and debug it

    – varit05
    Mar 23 at 4:52











  • Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

    – Ray Toal
    Mar 23 at 4:58






  • 1





    you dont' care why no error in the console?

    – Jaromanda X
    Mar 23 at 5:28






  • 1





    @skillitzimberg - you probably have a .catch block in code you didn't show

    – Jaromanda X
    Mar 23 at 5:45
















Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

– Khan Sharukh
Mar 23 at 4:52





Try changing let to var. It may be because the variable currentData and others are not within the scope of for-loop. Let me know if that works.

– Khan Sharukh
Mar 23 at 4:52




1




1





Add console.log inside for loop and debug it

– varit05
Mar 23 at 4:52





Add console.log inside for loop and debug it

– varit05
Mar 23 at 4:52













Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

– Ray Toal
Mar 23 at 4:58





Check your browser console. If the console.log is not running, then the promise's then callback did not fire. The console might have an error. Also consider adding a catch callback.

– Ray Toal
Mar 23 at 4:58




1




1





you dont' care why no error in the console?

– Jaromanda X
Mar 23 at 5:28





you dont' care why no error in the console?

– Jaromanda X
Mar 23 at 5:28




1




1





@skillitzimberg - you probably have a .catch block in code you didn't show

– Jaromanda X
Mar 23 at 5:45





@skillitzimberg - you probably have a .catch block in code you didn't show

– Jaromanda X
Mar 23 at 5:45












1 Answer
1






active

oldest

votes


















3














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.






share|improve this answer























  • That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

    – skillit zimberg
    Mar 23 at 5:24











  • @JaromandaX That wasn't in the question.

    – melpomene
    Mar 23 at 5:29






  • 1





    @JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

    – melpomene
    Mar 23 at 5:37











  • @JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

    – melpomene
    Mar 23 at 5:40












  • I won't bother any more

    – Jaromanda X
    Mar 23 at 5:43











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310693%2fvariable-not-available-after-for-loop-inside-promise-then%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














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.






share|improve this answer























  • That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

    – skillit zimberg
    Mar 23 at 5:24











  • @JaromandaX That wasn't in the question.

    – melpomene
    Mar 23 at 5:29






  • 1





    @JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

    – melpomene
    Mar 23 at 5:37











  • @JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

    – melpomene
    Mar 23 at 5:40












  • I won't bother any more

    – Jaromanda X
    Mar 23 at 5:43















3














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.






share|improve this answer























  • That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

    – skillit zimberg
    Mar 23 at 5:24











  • @JaromandaX That wasn't in the question.

    – melpomene
    Mar 23 at 5:29






  • 1





    @JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

    – melpomene
    Mar 23 at 5:37











  • @JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

    – melpomene
    Mar 23 at 5:40












  • I won't bother any more

    – Jaromanda X
    Mar 23 at 5:43













3












3








3







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.






share|improve this answer













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.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 23 at 5:11









melpomenemelpomene

63.7k55195




63.7k55195












  • That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

    – skillit zimberg
    Mar 23 at 5:24











  • @JaromandaX That wasn't in the question.

    – melpomene
    Mar 23 at 5:29






  • 1





    @JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

    – melpomene
    Mar 23 at 5:37











  • @JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

    – melpomene
    Mar 23 at 5:40












  • I won't bother any more

    – Jaromanda X
    Mar 23 at 5:43

















  • That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

    – skillit zimberg
    Mar 23 at 5:24











  • @JaromandaX That wasn't in the question.

    – melpomene
    Mar 23 at 5:29






  • 1





    @JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

    – melpomene
    Mar 23 at 5:37











  • @JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

    – melpomene
    Mar 23 at 5:40












  • I won't bother any more

    – Jaromanda X
    Mar 23 at 5:43
















That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

– skillit zimberg
Mar 23 at 5:24





That's it. Loops 101. I knew I was missing something simple. Or was at least hoping so. Thank you.

– skillit zimberg
Mar 23 at 5:24













@JaromandaX That wasn't in the question.

– melpomene
Mar 23 at 5:29





@JaromandaX That wasn't in the question.

– melpomene
Mar 23 at 5:29




1




1





@JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

– melpomene
Mar 23 at 5:37





@JaromandaX Yes, because it's not executed, because an exception was thrown earlier.

– melpomene
Mar 23 at 5:37













@JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

– melpomene
Mar 23 at 5:40






@JaromandaX Yeah, but OP didn't mention or ask anything about exceptions. Just console.log output. Where did you get that OP saw no error?

– melpomene
Mar 23 at 5:40














I won't bother any more

– Jaromanda X
Mar 23 at 5:43





I won't bother any more

– Jaromanda X
Mar 23 at 5:43



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310693%2fvariable-not-available-after-for-loop-inside-promise-then%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현