Call back methods with sqlite in node js - node.js

I'm trying to create a new program using node.js which reads SQLite DB and creates a XML document. I created some sub methods, and when I'm trying to return the DB result using a callback method its not passing anything.
Method to read and create xml part:
function dbpic(id,callback){
dd = db1.all("SELECT * FROM pictures left join item_pics on item_pics.picid=pictures.picid where item_pics.itemid = "+id+"", function(err1,rows1){
var ee = '';
rows1.forEach(function(row1) {
ee += '<picture>';
ee+='<picturename>'+row1.pic+'</picturename>';
ee+='<link>'+row1.url+'</link>';
ee += '</picture>';
});
console.log(ee);
callback( ee);
});
}
Calling this method using:
dbpic(row.iid,function(df){
ss += df;
});
Variable ss is going to display, but it gets nothing from callback method. Database contains relevant data and returning correct results results. I checked them using console.log.
When i logged df with console, it displays results correctly. but ss is not stored df's data.

According to your comments you have some troubles understanding the asynchronous concept. This how things happen in your code.
// STEP 1
ss = "initalvalue";
dbpic(row.iid,function(df){
// STEP 3, 4, 5, 6 ...
ss += df;
});
// STEP 2
ss += "ending";
You need to wait until the last callback is called until you display the results.

Related

Node.js Firestore forEach collection query cannot populate associative array

In this simplified example, associative array A cannot be populated in a Node.js Firestore query---it's as if there is a scoping issue:
var A = {};
A["name"] = "nissa";
firestore.collection("magic: the gathering")
.get()
.then(function(query) {
query.forEach(function(document) {
A[document.id] = document.id;
console.log(A);
});
})
.catch(function(error) {
});
console.log(A);
Console output:
{ name: 'nissa' } < last console.log()
{ name: 'nissa', formats: 'formats' } < first console.log() (in forEach loop)
{ name: 'nissa', formats: 'formats', releases: 'releases' } < second console.log() (in forEach loop)
Grateful for any assistance, please request for further detail if needed.
Data is loaded from Firestore asynchronously, and while that is happening, your main code continues to run.
It's easiest to see what that means by placing a few logging statements:
console.log("Starting to load data");
firestore.collection("magic: the gathering")
.get()
.then(function(query) {
console.log("Got data");
});
console.log("After starting to load data");
When you run this code, it prints:
Starting to load data
After starting to load data
Got data
This is probably not the order that you expected the logging to be in. But it is actually working as intended, and explains the output you see. By the time your last console.log(A); runs, the data hasn't been loaded yet, so A is empty.
The solution is simple, but typically takes some time to get used to: all code that needs the data from the database must be inside the callback, or be called from there.
So something like this:
var A = {};
A["name"] = "nissa";
firestore.collection("magic: the gathering")
.get()
.then(function(query) {
query.forEach(function(document) {
A[document.id] = document.id;
});
console.log(A);
})
Also see:
Array of JSON object is not empty but cannot iterate with foreach, show zero length
NodeJS, Firestore get field
Unable to add Google markers inside a loop, a more complex problem, calling multiple asynchronous API
scope issue in javascript between two Functions, which also shows using the more modern async and await keywords, instead of then()
How to get data from firestore DB in outside of onSnapshot, which uses an onSnapshot listener instead of get()

how to handle nested for each loop which contain callback using sails.js

I have pseudo code -
foreach(clients){
foreach(orderids)
{
//call asynchronous findOne()
if(client_Has_OrderId){
count++;
}
}//close foreach orderids
storeInArray(client,count);
}//close client foreach loop
I am new on sails.js and don't know how to code this in sails.js I have no experience of asynchronous programming.When I code this in synchronous way desire result not get.
result should look like-
client1 1
client2 5
client3 0
Thank you.
I want to recommend you to have a look at the sails reference and also the concepts section.
It always depends on your setup: I assumed you have set up a foreign key to your orders (see OneToMany), so you can just populate your values and directly access them in the promise, which would be the optimized way to query your desired result.
ES 5 compatible code could look like:
Note that I am using lodash (or underscore) for validating the array - which is included by default in sails.js if you did't disable it in the config.
Client.find({your:'criteria'})
.populate('orders')
.then(function(clients){
var orderIndex = {};
_.forEach(clients, function(client, index){
if(!_.isArray(client.orders)) {
orderIndex[client.id] = 0;
} else {
orderIndex[client.id] = client.orders.length;
});
// do something with [orderIndex]
})
.catch(function(e){
console.log(e);
})

Variable outside callback is empty [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'm a NodeJS beginner and actually I try to work with a NoSQL Database for building a simple login via. Digest Authentication. I also created an module called "users" wich is loaded in my application.
Now when I try to call the data results inside the callback function I get my correct data. In the same callback I assign the returned data to the variable records. When I call the variable outside I will get the result null - where is the error?
var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null
dbfile.top(1000).callback(function(err, response) {
(function(users) {
records = users
console.log(users) // Here i get the wanted result
})(response)
})
console.log(records) // Here the result is empty
thank you very much :)
Since the you are calling console.log(users) inside the callback, the value is reflected correctly. And this is a behavior of asynchronous calls in javascript. So the last line console.log(records) would probably be run first before the callback executes and so records up to this point does not have any value.
So I would suggest that you make the a function that does something on users and call it inside the callback.
var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null
dbfile.top(1000).callback(function(err, response) {
(function(users) {
//records = users
//console.log(users) // Here i get the wanted result
doSomethingToUsers(users);
})(response)
})
function doSomethingToUsers(users) {
// do something to users
}
//console.log(records) // Here the result is empty
Looks like a timing issue to me. When console.log(records) in the outer scope gets called before the (async) callback function was called, records contains exactly the value that was initially assigned (records = null).
Only after calling the async callback, the records variable will be set.
Does this help?

In node.js, how do I make a asynchronous callback in this situation

Firstly, I have a array of data in json, for example,
var a = [{'name':'jack','age':15},{'name':'tom','age':30}];
And what is more, I have a mongodb based database, which is implemented in mongoose. Inside the database, there is a user collection storing user's other information.
So right now, I want to query the information in a list of people shown above.
for(var i=0;i<a.length;i++){
console.log('time schedule '+" "+a[i].name+" "+a[i].age);
model.findOther(a[i].name,function(err,data){
// I can get the data from mongodb
console.log("time schedule data:"+" "+data.otherinfo+" ");
--------------------------------------------------------------------------------
//however the problem arises that I can not get the a[i].age inside the callback
console.log(a[i].age );
});
}
I know it is kind of wrong to get the right data, so could anyone help me how to write the code in asynchronous way?
You have to put your function into a closure and push the related variable as a parameter into it:
for(var i=0;i<a.length;i++){
console.log('time schedule '+" "+a[i].name+" "+ai].age);
(function(item){
model.findOther(item.name,function(err,data){ // <-- here you could use 'a[i]' instead of 'item' also
console.log("time schedule data:"+" "+data.otherinfo+" ");
console.log(item.age ); // <-- here you must use 'item'
});
}(a[i])); // <-- this is the parameter of the closure
}

copy values from sqlite3 db to a global array in node.js

i have use the node_sqlite3 module and i have try the following example:
var sqlite = require('sqlite3').verbose();
var db = new sqlite.Database("/var/www/signals/db/app3.db");
var matrixSignals = new Array();
var i;
i = 0;
db.all('SELECT * FROM tbl_signals', function(err,rows){
rows.forEach(function(row) {
matrixSignals[i] = new Object();
matrixSignals[i].signalID = row.signalID;
matrixSignals[i].connID = row.connID;
i++;
});
db.close();
console.log('1:' + matrixSignals.length);
});
console.log('2:' + matrixSignals.length);
in the console output 1 the length is correct but in the console output 2 the length is always 0. How i will set the matrixSignals as a global variable?
The reason this doesn't work has to do with how Node.js operates in general. In node, all code is executed asynchronously; at the time you are logging output 2, matrixSignals still has a length of 0. This is because after you fire off the database query, the code continues to execute. Logging output 1 is only executed after the database query has finished, which is why it returns the correct results.
For this reason, the simple answer to your question is that there is no way to set matrixSignals to be a global variable. If all of your logic is truly dependent on the values in that array, then your logic should be in the callback to the database call - so that it only executes that code once the data has been retrieved from the database. If you just want the syntax to be cleaner, you could potentially use something like node-promise (https://github.com/kriszyp/node-promise) but I think that's probably more effort than its worth.

Resources