I have function
var checkTokenIsExpired = function(name, token, response) {
LoginToken.find( { name: name, series: token }, function(error, info){
console.log("info: ", info[0]['expire']);
if (error) {
// response.send("error: %s}", error);
response(error);
}
if (info.length > 0) {
var expire = new String(info[0]['expire']);
// expire = expire.substr(0,26);
var date = new Date(expire);
if (date >= new Date()) {
// response.send("{info: success" );
response("success");
}
else{
// response.send("error: token-has-expired");
response("token-has-expired");
}
console.log("Response: ", info);
}
else {
response(null);
}
} );
}
To check token is expired or not? It will return a string.
And I call this function in here
exports.updateAccount = function(newData, callback)
{
Accounts.find({name:newData.body.name}, function(err, docs){
if (err) {
callback.send('{error: ' + String(err) + "}");
}
if (docs.length==0 || !docs) {
callback.send("{error: NULL }");
}
else {
checkTokenIsExpired(newData.body.name, newData.body.token, function(error, info){
if (error){
callback.send("{error: " + error + "}");
// I want to get info here }
console.log("check token: ", info);
// check info of token is expired or not
if (info!=null && info!="token-has-expired") {
var updateString = "";
if (newData.body.screen_name){
Accounts.update( {'name': newData.body.name},
{
"screen_name" : newData.body.screen_name
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
if (newData.body.email){
Accounts.update( {'name': newData.body.name},
{
"email": newData.body.email
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
if (newData.body.password == ''){
} else{
var password = encodePassword(newData.body.password, docs[0]['salt']);
Accounts.update( {'name': newData.body.name},
{
"hassedPass" : password,
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
}
});
}
I want to get the info when call checkTokenIsExpired but when I console.log("info", info) it return undefined.
in checkTokenIsExpired, you need to pass info to the response callback otherwise it is not in scope of your second code.
at least in the case where you have success:
response("success", info);
Instead of passing "success", you'd typically pass null to indicate there is no error.
I have solved problem
checkTokenIsExpired(newData.body.name, newData.body.token, function(error, info)
because it will take 1 parameter but I put 2
Change it into checkTokenIsExpired(newData.body.name, newData.body.token, function(info)
It will correct :D
Related
I'm trying data extraction in Node.js with Firebird.
First code:
var sql1 = 'select id,id_asset_element,duration,start_datetime,show_name from MAIN_EVENT where start_datetime > DATEDIFF(millisecond, TIMESTAMP\'0001-01-01 00:00\', CURRENT_TIMESTAMP) and id_playlist=1 order by 1 asc;'
app.get('/', function(req, res) {
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql1, function(err, result) {
// IMPORTANT: close the connection
console.log(result())
db.detach();
res.render('pages/index', {
result : result
});
if(err)
console.log(err)
});
});
})
And first log:
{
ID: 744636,
ID_ASSET_ELEMENT: 86869,
DURATION: 27000,
START_DATETIME: 63760068424160,
SHOW_NAME: 'CHID, CLIP'
},
{
ID: 744637,
ID_ASSET_ELEMENT: 81723,
DURATION: 96120,
START_DATETIME: 63760068451160,
SHOW_NAME: 'CHID, CLIP'
},
This result is good.
Second Code:
var sql2 = 'select IMPORT_FIELDS from MAIN_EVENT where start_datetime > DATEDIFF(millisecond, TIMESTAMP\'0001-01-01 00:00\', CURRENT_TIMESTAMP) and id_playlist=1 order by 1 asc;'
app.get('/test/', function(req, res) {
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql2, function(err, result) {
// IMPORTANT: close the connection
console.log(result)
db.detach();
res.render('pages/test', {
result : result
});
if(err)
console.log(err)
});
});
})
And second log:
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
If I open, localhost:3000/test result is this:
function(callback) { // callback(err, buffer, name); statement.connection.startTransaction(ISOLATION_READ_UNCOMMITTED, function(err, transaction) { if (err) { callback(err); return; } statement.connection._pending.push('openBlob'); statement.connection.openBlob(id, transaction, function(err, blob) { var e = new Events.EventEmitter(); e.pipe = function(stream) { e.on('data', function(chunk) { stream.write(chunk); }); e.on('end', function() { stream.end(); }); }; if (err) { callback(err, name, e); return; } function read() { statement.connection.getSegment(blob, function(err, ret) { if (err) { transaction.rollback(function() { e.emit('error', err); }); return; } if (ret.buffer) { var blr = new BlrReader(ret.buffer); var data = blr.readSegment(); e.emit('data', data); } if (ret.handle !== 2) { read(); return; } statement.connection.closeBlob(blob); transaction.commit(function(err) { if (err) { e.emit('error', err); } else { e.emit('end'); } e = null; }); }); } callback(err, name, e); read(); }); }); } function(callback) { // callback(err, buffer, name); statement.connection.startTransaction(ISOLATION_READ_UNCOMMITTED, function(err, transaction) { if (err) { callback(err); return; } statement.connection._pending.push('openBlob'); statement.connection.openBlob(id, transaction, function(err, blob) { var e = new Events.EventEmitter(); e.pipe = function(stream) { e.on('data', function(chunk) { stream.write(chunk); }); e.on('end', function() { stream.end(); }); }; if (err) { callback(err, name, e); return; } function read() { statement.connection.getSegment(blob, function(err, ret) { if (err) { transaction.rollback(function() { e.emit('error', err); }); return; } if (ret.buffer) { var blr = new BlrReader(ret.buffer); var data = blr.readSegment(); e.emit('data', data); } if (ret.handle !== 2) { read(); return; } statement.connection.closeBlob(blob); transaction.commit(function(err) { if (err) { e.emit('error', err); } else { e.emit('end'); } e = null; }); }); } callback(err, name, e); read(); }); }); } function(callback) { // callback(err, buffer, name);
Problem
How can I extract [Function (anonymous)] from second log.
I'm using,
Node.js, Express, Ejs and Firebird.
Update :
npmjs.com/package/node-firebird
I found how to display blob data. This code is working for me.
select cast(BLOBDATANAME as varchar(1000) character set utf8)
Firebird-Nodejs
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql2, function(err, result) {
// IMPORTANT: close the connection
console.log(result)
db.detach();
if(err)
console.log(err)
});
});
Result:
{ CAST: '<XML></XML>' }, { CAST: '<XML></XML>' }, { CAST: '<XML></XML>' },
Thanks all, regards.
I am trying to develop an APP in which I have to increase or decrease the user count according to their hobbies/interest in the master list. I am doing it in Node js with the help of loopback. Here is my code, in which I am giving two interests(i.e sketching and horse-riding):
async.forEach(data, function (interest) {
console.log("Interest is", interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
//return callback(err, null);
console.log("error", err);
}
else {
//return callback(null, response);
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
}
});
// return callback(null, {});
},function(err){
console.log("success..!!")
});
}
but it is showing me only one of them in output. Here is output:
data is [ 'horse-riding', 'skeching' ]
Interest is horse-riding
Interest is skeching
found { name: 'horse-riding', count: 1, id: 59ccff0765055a212491a6bc }
found null
I think the async function is not working properly with forEach loop in this, But I am not getting where the code went wrong. I want to show all the interest given by the user, so what course of actions should I take to do it?? Thanks in advance..!!:)
It is working now...!!!
async.each(data, function (interest, callback2) {
console.log('Processing ', interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
console.log("error", err);
callback2(err);
}
else {
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
callback2();
}
});
}, function (err) {
if (err) {
console.log('Failed to process', err);
} else {
console.log('All interests have been processed successfully');
}
return callback(err);
})
};
in this function we get id from Mongo Database and process function to put varriable in GetID varriable
"callback is not function"
var GetID = function( nameval , callback ){
console.log(nameval);
console.log("munesh hello");
var result = GenerateID.find({ "id_name" : nameval },{"id_code":1 , "id_value":1 , "_id":0},function( err , genvalue ) {
if ( err )
{
console.log('error has been occured');
//throw err;
}
else {
if(genvalue === null)
{
callback( err , false );
}
else
{
console.log(genvalue);
//calling this function
callback( err , true );
}
}
// console.log(genvalue);
});
console.log('munesh kumar');
// console.log(result);
console.log('kumar');
};
When calling GetID, you are not sending 2 parameters (nameval and callback). You are only sending the first parameter:
var region_id = GenerateID.GetID( name );
Instead this is how you should call the function:
GenerateID.GetID(name, function(error, result) {
if(error) {
// handle error
} else {
if(!result) {
// not found
} else {
// do something with result
}
}
});
Remember that you are dealing with asynchronous functions. You cannot return output directly from an asynchronous function (GetID). Instead you have to pass it to the callback function.
Your GetID function should be something like this:
var GetID = function(nameval, callback) {
GenerateID
.find({ "id_name": nameval }, { "id_code": 1, "id_value": 1, "_id": 0 }, function(err, genvalue) {
if (err) {
callback(err);
} else {
if (genvalue === null) {
callback(null, null); // no document found
} else {
callback(null, genvalue);
}
}
});
};
var region_id = GenerateID.GetID( name , function(error, result) {
if(error) {
// handle error
console.log("getting any error");
} else {
console.log(region_id);
if(!result) {
console.log('data is not coming');
} else {
console.log('data is coming');
}
}
});
get id function are below var GetID =function( nameval ,callback){
console.log(nameval);
console.log("munesh hello");
GenerateID.find({ "id_name" : nameval },{"id_code":1 , "id_value":1 , "_id":0},function( err , genvalue ) {
if (err) {
console.log('hello');
// callback(err);
} else {
if (genvalue === null) {
console.log('123');
callback(null, null); // no document found
} else {
console.log('456');
callback(null, genvalue);
}
}
});
};
calling id from mongodb with callback function
var GetID = function (nameval, callback) {
console.log(nameval);
console.log("munesh hello");
GenerateID.find({ "id_name": nameval }, {
"id_code": 1,
"id_value": 1, "_id": 0
}, function (err, genvalue) {
if (err) {
console.log('hello');
}
else {
if (genvalue === null) {
callback(err, false);
}
else {
callback(err, true);
}
}
console.log(genvalue);
});
};
and calling above method so we need
so we need id from GenerateID.GetID and do our own work.
var region_id = GenerateID.GetID(name, function (error, result) {
if (error) {
console.log("getting any error");
} else {
console.log(region_id);
if (!result) {
console.log('data is not coming');
} else {
console.log('data is coming');
}
}
});
You have a number of issues. In the first piece of code, you need to pass the actual value when calling the callback.
In the second, you need to set region_id = result.
Ideally you would do this using promises as demonstrated below.
var GetID = function(nameval){
return new Promise((resolve,reject) => {
console.log(nameval);
console.log("munesh hello");
GenerateId.find({ "id_name" : nameval },{"id_code":1 , "id_value":1, "_id":0},
function( err , genvalue ) {
console.log(genvalue);
if (err) {
console.log('hello');
return reject()
}
if (genvalue == null) { return resolve(false); }
return resolve(genValue);
});
});
}
var GetIDPromise = GenerateId.GetID(name);
GetIDPromise.then(
genValue => {
if ( genValue == false ){
console.log('data is not coming');
// handle region id not being available. Perhaps return and show an error
}else{
var region_id = genValue;
// continue execution and use region id.
}
},
error => {
console.log("getting any error");
}
)
I have this code:
async = require('async')
async.auto({
getUserName: function(callback) {
console.log('**In getUserName.**')
callback(null, 'Lem')
},
connectToDb: function(callback) {
console.log('**In connectToDb.**')
var connected = true
if(connected) {
callback(null, connected)
} else {
callback('Error connecting to DB.', null)
}
},
checkIfUserExist: [
'getUserName',
'connectToDb',
function(callback, results) {
console.log('**In checkIfUserExist.**',
JSON.stringify(results))
var userExist = false
if(userExist) {
callback('User exist in DB.')
} else {
setTimeout(
function() {
callback(null, userExist);
},
1000
);
}
}
],
signup: [
'checkIfUserExist',
function(callback, results) {
console.log('**In signup**', JSON.stringify(results))
var userName = results.getUserName
var isDbConnected = results.connectToDb
var userExist = result.checkIfUserExist
if(userName && isDbConnected && !userExist) {
callback(null,
{'status': '200', 'msg': 'Successfully signed up user'})
} else {
callback('Error signing up user.', null)
}
}
]
},
function(error, results) {
console.log('error = ', error)
console.log('results = ', results)
})
Why am I experiencing this error:
**In getUserName.**
**In connectToDb.**
error = function () {
if (fn === null) throw new Error("Callback was already called.");
var callFn = fn;
fn = null;
callFn.apply(this, arguments);
}
results = undefined
**In checkIfUserExist.** undefined
^[[A/home/lem/js/async/asyncAuto.js:30
callback(null, userExist);
^
TypeError: callback is not a function
at Timeout._onTimeout (/home/lem/js/async/asyncAuto.js:30:13)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
There was a breaking change in async's auto method in v2, which you seem to use.
https://github.com/caolan/async/blob/master/CHANGELOG.md#breaking-changes
auto task functions now always take the callback as the last argument. If a task has dependencies, the results object will be passed as the first argument. To migrate old task functions, wrap them with _.flip
An async function, one that expects a callback as its last argument. Here is my working code.
var async = require('async');
async.auto({
getUserName: function(callback) {
console.log('**In getUserName.**')
callback(null, 'Lem')
},
connectToDb: function(callback) {
console.log('**In connectToDb.**')
var connected = true
if(connected) {
callback(null, connected)
} else {
callback('Error connecting to DB.', null)
}
},
checkIfUserExist: [
'getUserName',
'connectToDb',
function(results, callback) {
console.log('**In checkIfUserExist.**',
JSON.stringify(results))
var userExist = false
if(userExist) {
callback('User exist in DB.')
} else {
setTimeout(function() {
callback(null, userExist);
},1000);
}
}
],
signup: [
'checkIfUserExist',
function(results, callback) {
console.log('**In signup**', JSON.stringify(results))
var userName = results.getUserName
var isDbConnected = results.connectToDb
var userExist = results.checkIfUserExist
if(userName && isDbConnected && !userExist) {
callback(null,
{'status': '200', 'msg': 'Successfully signed up user'})
} else {
callback('Error signing up user.', null)
}
}
],
},
function(error, results) {
console.log('error = ', error)
console.log('results = ', results)
})
function(callback, results) should be function(results, callback)
Please check this url for reference.
https://caolan.github.io/async/docs.html#auto