Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

breaks scope #2549

Closed
davidbdyer opened this issue Feb 3, 2022 · 3 comments
Closed

breaks scope #2549

davidbdyer opened this issue Feb 3, 2022 · 3 comments

Comments

@davidbdyer
Copy link

i have an array variable declared outside of my function and my function pushes on to that array except only inside of the function outside of the function the variable is empty. Anyone know why?

connection.query(returnBranchNames, function(error, results) {
	if (error) throw error
	results.forEach(function(elm) {
		branchName.push(elm.branch_name);
	})
})
@dougwilson
Copy link
Member

Hi @davidbdeath sorry you are having trouble. That is a general Node.js / JavaScript question, unrelated to this module. You can read more about this in the Node.js guide https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/

@davidbdyer
Copy link
Author

Hi @dougwilson thanks for the quick response. I'm a little bit of a noob. I'm confused why it will output to console.log and push onto the variable locally inside the function but doesn't push onto it globally even though it's the same variable. I read the link but it's still a bit fuzzy. Do i need to create an async function? If you're too busy to explain I wont keep asking. My prof is good at mysql but not so much with javascript.

@dougwilson
Copy link
Member

Hi @davidbdeath no problem. The issue is that with non-blocking operations that are common in Node.js (typically styled as a "callback"), the code does not run linear top-to-bottom -- the code inside the callback will run at a later time. So thus in the example like

console.log(1)
conn.query('SELECT 1', function () { // this is a callback
  console.log(2)
})
console.log(3)

The output will be 1, then 3, then 2. So if you declare a variable at 1, then manipulate it at 2, at 3, you won't see the value, since 3 ran before you did the manipulation, even though reading the file top-to-bottom looks like it may happen before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants