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;
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
|
show 8 more comments
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
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 theconsole.log
is not running, then the promise'sthen
callback did not fire. The console might have an error. Also consider adding acatch
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
|
show 8 more comments
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
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
javascript for-loop asynchronous scope
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 theconsole.log
is not running, then the promise'sthen
callback did not fire. The console might have an error. Also consider adding acatch
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
|
show 8 more comments
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 theconsole.log
is not running, then the promise'sthen
callback did not fire. The console might have an error. Also consider adding acatch
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
|
show 8 more comments
1 Answer
1
active
oldest
votes
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
.
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. Justconsole.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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
.
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. Justconsole.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
add a comment |
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
.
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. Justconsole.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
add a comment |
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
.
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
.
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. Justconsole.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
add a comment |
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. Justconsole.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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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'sthen
callback did not fire. The console might have an error. Also consider adding acatch
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