I am playing around with some nodeJs things, I read about block and functions scooping but I was not able to access my variable jsonArrayObj:
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
console.log(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err) => {
console.log(err);
});
console.log('jsonArrayObj'); // I want to print the results here also
You can do it something like this.
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
console.log(jsonArrayObj);
myNewFunc(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err)=>{
console.log(err);
});
var myNewFunc = function(myVar){
console.log(myVar); // this will be your result
};
Your variable jsonArrayObj is just defined on your function's scope. So jsonArrayObj is just accessible in your function.
If you want to use it out of your function, you have to define a variable outside of your function, and then tell your function that this variable takes jsonArrayObj's value.
Like this :
var myRes;
csv({delimiter: [' ']})
.fromFile(csvFilePath)
.on('end_parsed', function(jsonArrayObj) {
myRes = jsonArrayObj;
console.log(jsonArrayObj);
function cssResult() {
return jsonArrayObj;
}
})
.on('error', (err)=>{
console.log(err);
});
console.log(myRes);
Related
function collectres () {
var store ='';
var docRef = db.collection("cities").doc("SF");
docRef.get()
.then(function (doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
store = doc.data();// when referenced outside, it doesnt hold anything.
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function (error) {
console.log("Error getting document:", error);
});
return store; // returns nothing and seems to not notice the assignment.
}
I have this problem, where i want to store firebase query results into a variable. However, when i try and assign the variable some data from the query, it seems to not be able to store it.
Any help or advice in the right direction would help.
Edit 1:
After implementing the callback function, i was wondering how to set the state for a component or permanently store the results so that many components can access it.
user.CollectRes(function(store){
console.log(store.name);
name =store.name;
console.log(name);
// this.setState({name:store.name});
});
console.log(name); // want to be able to reference this outside the callback function. So i can display it on the page.
It is because JavaScript is asynchrone.
Because of that, your variable doc doesn't exists yet outside your .then function.
To return this value, you can use Promises way, or easier, you can have a callback function to return your document like this :
function collectres (callback) {
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function (doc) {
if (doc && doc.exists) {
callback(doc.data()); // Return your data inside the callback function
} else {
callback(null); // Return null if data doesn't exists
}
}).catch(function (error) {
callback(null); // Return null in error case
});
}
collectres(function (store) { // Call collectres to get your data
console.log(store);
// continue here
});
I recommand you to read this article to learn more about asynchronous.
Hope it helps.
I am trying to store the result from imap.fetch() into a variable, so that i can iterate it whenever i want to check all mail.
But it is not working when i call my getAllMail() from another class, Thanks for any help.
let allSearch;
imap.search(['All', ['ON', date]], (err,res) => {
if (err) console.log(err)
else {
allSearch = imap.fetch(res, {bodies:'HEADER.FIELDS (FROM SUBJECT)', struct:true})
}
})
function getAllMail() {
allSerch.on('message', (msg, seq) => {
console.log()
})
}
module.exports.getAllMail = getAllMail
this question is related with an answer to my previous question. there #robertklep recommends me to use mapLimit() instead of .map() because .map() can't handle a large series of data, and with that solution all works fine. But now I restructured my code, and now neither of the .<fn>Limit() functions run after the first loop iteration. do I missing something here?
var proccesBook = function(file, cb) {
testFile(file, function (epub) {
if (epub) {
getEpuData(file, function (data) {
insertBookInDB(data)
})
}else{
cb(file)
}
})
}
async.mapLimit(full_files_path, 10, proccesBook, function(err){
if(err){
console.log('Corrupted file', err);
} else {
console.log('Processing complete');
};
})
// ---> only runs for the first 10 series data
Your primary issue is you don't call cb in the success branch of processBook. Your control flow must guarantee to call the callback exactly once for each worker function invocation.
Other asides:
You don't seem to need the results, so eachLimit is fine
Only need mapLimit if you need the results of each worker
You need to follow the standard error-first convention when calling the callback. Don't do cb(file) as that will be interpretted as an error and about the remaining processing.
var proccesBook = function(file, cb) {
testFile(file, function (epub) {
if (epub) {
getEpuData(file, function (data) {
insertBookInDB(data)
cb() // This is what you were missing
})
}else{
cb()
}
})
}
async.eachlimit(full_files_path, 10, proccesBook, function(err){
if(err){
console.log('Corrupted file', err);
} else {
console.log('Processing complete');
};
})
I have return the function in mysql.js as :
function myFunction(resourceIdentifiers,callback){
dbconnection.execute( function(err,response) {
response.query('call SP_ExposePricingDetailforUI('
+ resourceIdentifiers + ')'
,function (err, rows, fields) {
console.log(rows);
});
}
);
return rows;
}
And tried to call it at another script file restservice.js as :
mysql.myFunction(resourceIdentifiers , function(err,rows) {
console.log(rows);
}
But I get error as the function myFunction is Undefined.
If mysql.myFunction is undefined, then you're probably not actually exporting it:
function myFunction(resourceIdentifiers, callback){
// ...
}
exports.myFunction = myFunction;
Function and variable declarations are "private" to the module by default. Only those members you explicitly export will be accessible from other modules.
You also won't be able to use return rows; as you're trying to. Asynchronous code is event driven and doesn't wait, which return would need it to do.
myFunction already has a callback argument and you're passing a function for the value. You just need to call it:
// ...
function (err, rows, fields) {
callback(err, rows);
}
// ...
You should also at least escape resourceIdentifiers when concatenating.
But, generally better is to use a placeholder (?) and the optional, 2nd argument to .query():
response.query(
'call SP_ExposePricingDetailforUI(?)',
[ resourceIdentifiers ],
function (err, rows, fields) {
callback(err, rows);
}
);
You just need to callback within the result of response.query. Something like this.
mysql.js:
function myFunction(resourceIdentifiers,callback){
dbconnection.execute( function(err,response) {
response.query('call SP_ExposePricingDetailforUI('
+ resourceIdentifiers + ')'
,function (err, rows, fields) {
callback(err, { rows: rows, fields: fields});
});
}
);
}
module.exports.myFunction = myFunction;
restservice.js:
mysql.myFunction(resourceIdentifiers , function(err,resp) {
console.log(resp.rows);
}
Update - removed the return rows statement that I missed the first time around.
ModuleTwo.js
exports.getNotificatiosById = function (notificationId) {
db.get(notificationId, function (err, doc) {
if(!err){
return true;
}
});
};
In modulelOne i need to get the result of the moduleTwo method.If moduleTwo method doesn't have the database query function means i can get that method result like below in moduleOne
var res=require('./lib/moduleTwo').getNotificatiosById;
If that db.get method has the synchronize method means i can do the query like
db.getSync(id);
Is there any other way to get the result of my moduleTwo method.Now i'm trying like below.Is it correct
moduleOne.js
var moduleTwo=require('./lib/moduleTwo');
moduleTwo.getNotificatiosById(id,function(err,res){
if(!err){
console.log('Result of the 2nd module is '+res);
}
});
You need to change getNotificatiosById to take a callback
exports.getNotificatiosById = function (notificationId,callback) {
db.get(notificationId, function (err, doc) {
if(!err){
callback(doc);
return true;
}
});
};
Then call it like
var moduleTwo=require('./lib/moduleTwo');
moduleTwo.getNotificatiosById(id,function(res){
console.log('Result of the 2nd module is '+res);
});