Setting global array from inside readFile [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I'm probably missing something simple here, but for some reason, when I set an array's value from inside a function, I can no longer read that array once outside of that function.
var threadArray = [];
function getThreads() {
var fs = require('fs');
// read list of threads
fs.readFile('./database/threadList.txt', function(err, data) {
var threadIds = data.toString().split("\n");
for(i in threadIds) { threadArray[i] = threadIds[i].split(","); }
console.log("This works: " + threadArray[0])
})
console.log("This does not work: " + threadArray[0] + " Returns [undefined]")
}
What am I missing here? I'm assuming something to do with the way I declared the array?

This is a timing issue. fs.readFile is an asynchronous operation - your second console.log that doesn't work is getting processed immediately after fs.readFile starts running and your threadArray is not yet populated. You can use fs.readFileSync instead
try {
var threads = fs.readFileSync('./database/threadList.txt');
var threadIds = threads.toString().split('\n');
for(i in threadIds) {
threadArray[i] = threadIds[i].split(",");
}
console.log("This works: " + threadArray[0]);
} catch (e) {
console.error("Error reading file: ", e);
}

Related

How can I update the global variable from inside a function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have the following code
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
console.log(priceNow)
});
But I need to use the variable "priceNow" outside of that function, I have tried many things, for example:
var priceNow = ""
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
// console.log(priceNow)
});
console.log(priceNow) //But this just say nothing
But this doesn't work, I can't update the global variable from the function, why does this happen? and because if it works in example like this:
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
console.log("Value of 'a' outside the function " + a); //outputs 20

How to make a line wait for function return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have 2 files
//init.js
var x = getMasterList(location);
console.log(x);
console.log("should have printed list");
And
//read.js
function getMasterList(location) {
var list = [];
ref.child(company).child("listOfLocations").once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
list.push(item);
})
});
console.log("In function");
return list;
}
The console's output is
undefined
should have printed list
In function
The problem is, because of javascript's asynchronous nature, it prints out 'x' before assigning it. I've looked at promises and it doesn't seem like it can help me since it didn't change the async behaviour. I've also looked at callbacks and I can't seem to make them work for multiple files.
Any ways of getting around this so that it only prints after 'x' has a value?
Using callbacks, you can achieve this quite easily.
read.js
function getMasterList(location, callback) {
var list = [];
//do stuff
console.log("In function");
callback(list);
}
init.js
var x = getMasterList(location, function(x){
console.log(x);
console.log("should have printed list");
});

No var assignment outside scope in Javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I need to understand how come the assignment of vm.Info var does not work properly. Sorry for the bad question.
vm.getUser = function(email) {
vm.Info = ''
authentication
.avvocatoByEmail(email)
.error(function(err){
return null;
}).success(function(data){
vm.data = { user : data };
vm.Info = $crypto.encrypt(vm.data.user[0].id + "." + vm.data.user[0].email, 'myKey');
console.log("Here ok: " + vm.Info);
});
console.log("Here blank: " + vm.Info);
}
Because ajax call is asynchronous, and as a result, your second console.log (which isnt working) will get executed first; And once success event of ajax call is fired, the first console.log will work where you are assigning data to that variable.

Retrieve value from nested functions javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I have had a look, and see some great examples of nesting functions, but even with reading them, I cannot see why I am getting undefined when i call this function:
function readBttnDetec() {
var devid = localStorage.getItem('vBttn');
var bd = 0;
bd = ble.read(devid, 'fffffff0-00f7-4000-b000-000000000000',
'FFFFFFF2-00F7-4000-B000-000000000000',
function(t) {
var data = new Uint8Array(t)
console.log('returns: ' + data[0]); // this returns 6
return data[0];
}, function(f) {
console.log(f);
});
return bd;
}
This is the call:
//check button state
var detecs = readBttnDetec();
console.log(detecs);
if(detecs == 2) {
// fall detection disabled
$('#playfall').removeClass('km-state-active');
} else if(detecs == 6) {
// fall detection enabled
$('#playfall').addClass('km-state-active');
} else {
// error reading button
}
I am missing something simple I am sure of it, but I cannot see it.
Thanks in advance

javascript: function returns value undefined when assigned to variable [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I'm trying to assign a function's return value to a variable, using this stackOverflow article as a template. Here's my code:
var host = getHostName(djId, function(name) {
return name;
});
console.log(host); // undefined :(
function getHostName(id, cb) {
var reply;
userColl.findById(id, function (err, dj) {
if (err) {
reply = "db error";
} else {
reply = dj.firstName + ' ' + dj.lastName;
}
console.log(reply + ' reply'); // working as expected!
cb(reply);
});
}
the console.log(reply) is working as expected but host is still undefined when i try t call the function. what gives?
Because it's the result of getHostName which itself doesn't return anything. It seems like an asynchronous function, so if you need to do something with the value, you have to put it inside of the callback.
The inner function (callback) is executed asynchronously so when it runs, the execution of getHostName is already finished. And that's why the inner function can't return anything to the variable. All code, which will do something with the name, has to be inside of the callback.
var host = getHostName(djId, function(name) {
console.log(name); // Here you go
anotherFn(name); // Here you can have the rest of your code which needs the name
});

Categories

Resources