I have this code with callbacks:
function getUserToken(data, callback) {
var password_sha256 = sha256(data.password);
getAppById(data.app_id).then(function(res) {
console.log("app"+res);
if (!res) {
console.log("No app");
callback(err, { meta: {
code: 403,
error_message: "There are no app with your id!"
} });
} else {
if (res.user_password == password_sha256) {
console.log("user found");
callback(err, { meta: { code: 200 },
token: password_sha256,
type: 1 });
return;
} else if (res.owner_password == password_sha256) {
console.log("owner found");
callback(err, { meta: { code: 200 },
token: password_sha256,
type: 0 });
} else {
console.log("user not found");
callback(err, { meta: {
code: 403,
error_message: "There are no users with your password!"
} });
}
}
});
}
I post some data using this function:
router.post('/api/login', (req, res) => {
db.getUserToken(req.body, function(err, result) {
console.log(result);
if (result.error) {
return res.status(403).send(result);
} else {
return res.status(200).send(result);
}
});
});
And then getUserToken found, for example, user, so I have "user found" in console log, but callback function in /api/login not working. Where is my error and how can I fix them?
Instead of callback, you can return a Promise, either native or using an external library like Kris Kowal Q
var Q = require('q');
function getUserToken(data) {
var deferred = Q.defer();
var password_sha256 = sha256(data.password);
getAppById(data.app_id).then(function(res) {
if (!res) {
deferred.reject("There are no app with your id!");
} else {
if (res.user_password == password_sha256) {
deferred.resolve({
token: password_sha256,
type: 1
});
} else if (res.owner_password == password_sha256) {
deferred.resolve({
token: password_sha256,
type: 0
});
} else {
console.log("user not found");
deferred.reject("There are no users with your password!");
}
}
})
.catch(function(error) {
deferred.reject(error);
});
return deferred.promise;
}
Then simply process or catch error when you post data
router.post('/api/login', (req, res) => {
db.getUserToken(req.body)
.then(function(result) {
res.status(200).send(result);
})
.catch(function(error) {
res.status(403).send(error);
});
});
Instead of using callback(err, data) you should use callback(null,data).This will give you required output.
Related
I am using async parallel to get data from db in parallel.
When every task is returning the data I am storing it in local object.
From index.js I am calling cacheService.js .
In cacheService.js I am loading data from mysql database and mongo database in to cache object.
Whenever I am doing npm run local run. I am getting following error.
UNHANDLEDREJECTION Error: Callback was already called.
This error is coming from loadMongoData method of cacheService.js.
I have followed other answers on stackoverflow like adding else part
Here is code for cacheService.js.
'use strict';
var cache = [];
class cacheService {
async init() {
await this.loadMongoData();
}
loadMongoData(env, callback1) {
const _this = this;
console.log('Inside loadMongoData')
async.parallel(
{
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
}
});
},
task2: function (callback) {
groupDef
.find({})
.lean()
.exec(function (err, groupDefs) {
if (err) {
console.log('Inside err2')
logger.error('Error fetching groupDefs: ', util.inspect(err));
callback(null, err);
} else if (groupDefs) {
console.log('Inside ')
global.groupDefsWithRoles = groupDefs;
let _groupDefs = [];
_.each(groupDefs, function (groupDef) {
var data = {
value: groupDef._id,
label: `${groupDef._id}: ${groupDef.description}`
};
_groupDefs.push(data);
});
global.groupDefs = _groupDefs;
cache['groupDefs'] = _groupDefs;
logger.info('Loaded groupDefs: ', global.groupDefs.length);
callback(null, null);
}
});
},
task3: function (callback) {
jiraProjects.find({$or: [{archived: {$ne: true}}, {archived: {$exists: false}}]}).exec(function (err, jiraProjects) {
if (err) {
console.log('Inside error 3')
logger.error('Error fetching jiraProjects: ', err);
callback(null, err);
} else if (jiraProjects) {
console.log('Inside jira project')
let _jiraProjects = [];
_.each(jiraProjects, function (jiraProject) {
var data = {
value: jiraProject.key,
label: jiraProject.key,
issueType: jiraProject.issueType ? jiraProject.issueType : 'Bug'
};
_jiraProjects.push(data);
});
global.jiraProjectsList = _jiraProjects;
cache['jiraProjects'] = _jiraProjects;
logger.info('Loaded jira projects: ', global.jiraProjectsList.length);
callback(null, null);
}
});
},
task4: function (callback) {
console.log('Inside task4')
callback(null, null);
},
task5: function (callback) {
inputElements
.find({})
.lean()
.exec(function (err, inputElements) {
if (err) {
console.log('Inside error5')
logger.error('Error fetching inputElements: ', util.inspect(err));
callback(null, err);
} else if (inputElements) {
console.log('Inside inputelements')
global.INPUT_ELEMENTS_DEF = inputElements;
cache['INPUT_ELEMENTS_DEF'] = inputElements;
callback(null, null);
}
});
},
task6: function (callback) {
console.log('Inside task6')
sisp.loadProducts('', callback);
}
},
function (err, results) {
if (err) {
console.log('Inside final error')
logger.error("Something went wrong can't start the app: ", util.inspect(err));
callback1(null, err);
} else {
console.log('Inside final else')
logger.info('loaded all globals properly :)');
callback1(null, null);
}
}
)
}
}
export default new cacheService();
I think your problem cuz you use callback inside of promise.
Please change your code like this:
class cacheService {
async init() {
await new Promise((resolve, reject) => {
this.loadMongoData(env, (ignoreArg, error) => {
if (error) {
return reject(error);
}
resolve();
});
});
}
...
}
Tip: in the each task add statement else for call callback, because maybe your statement not handled and your code can't execute prefect
task1: function (callback) {
CriteriaDef.find({})
.lean()
.exec(function (err, criteriaDefs) {
if (err) {
console.log('Inside err 1')
logger.error('Error fetching CriteriaDef: ', util.inspect(err));
callback(err, null);
} else if (criteriaDefs) {
console.log('Inside criteriaDefs')
if (criteriaDefs.length && criteriaDefs.length > 0) {
console.log('Inside criteriaDefs 1')
global.CRITERIA_DEFS = criteriaDefs;
cache['criteria_defs'] = criteriaDefs;
}
callback(null, null);
} else {
callback(null, null);
}
});
},
trying to test nodejs module.export function that will return based on request but it throws below error any idea what is implemented wrong here its expecting error >
v1Transform.js
module.exports = async (req, res) => {
try {
const validateResponse = responseHandler(req.drugPriceResponse);
} catch (error) {
if (error instanceof AppError) {
res.status(error.response.status).send(error.response.payload);
} else {
res.status(500).send(defaultErrorResponse);
}
}
}
main.test.js
describe('v1Transform()', () => {
it('should return error if accounts are ommitted', () => {
try {
v1Transform(req);
} catch (error) {
expect(error.response).to.deep.equal({
status: 500,
payload: {
'status': 500,
'title': 'Internal Server Error',
'detail': 'Accounts are not valid'
}
});
}
});
});
Error
1) v1Transform()
should return error if prices are ommitted:
AssertionError: expected undefined to deeply equal { Object (status, payload) }
I have the Problem that the return is made before methodStatus is set to true (so the return is always false even when I can see 'success' in the console log)
function anmelden(username, userPassword){
var methodStatus = false;
var opts = {
filter: 'sAMAccountName=' + username,
scope: 'sub'
};
ldapClient.search('OU=secret,OU=secret,DC=secret,DC=secret', opts, function(err, res) {
res.on('searchEntry', function(entry) {
var userClient = ldap.createClient({url: 'ldap://secret:1111'});
userClient.bind(entry.object.dn + '', userPassword, function(err) {
if(err) {
console.log('failed')
methodStatus = false;
} else {
console.log('success')
methodStatus = true;
}
ldapBind();
});
});
console.log('end');
return methodStatus;
});
}
This is the console log:
end
success
Thank you for your help :)
it is because of asynchrony. the return is invoked before the callback of the res.on is invoked. there are a lot of ways to handle it, for example to add a callback to the anmelden and to invoke it when the work is done:
function anmelden(username, userPassword, callback){
var methodStatus = false;
var opts = {
filter: 'sAMAccountName=' + username,
scope: 'sub'
};
ldapClient.search('OU=secret,OU=secret,DC=secret,DC=secret', opts, function(err, res) {
res.on('searchEntry', function(entry) {
var userClient = ldap.createClient({url: 'ldap://secret:1111'});
userClient.bind(entry.object.dn + '', userPassword, function(err) {
if(err) {
console.log('failed')
methodStatus = false;
} else {
console.log('success')
methodStatus = true;
}
ldapBind();
});
});
res.on('end', function () {
callback(methodStatus);
});
});
}
and to invoke it in the way like this:
anmelden('user', 'pass', function (methodStatus){
console.log('the status is %s', methodStatus);
})
I have problem with my node.js bot to roulette. Bot is fully set up but when I launching it, it gives me error "Bot stopped with code null". Can someone help me to fix it?
Here is the error screenshot: http://i.imgur.com/zfZoMD4.png
Code:
function login(err, sessionID, cookies, steamguard) {
if(err) {
logger.error('Auth error');
logger.debug(err);
if(err.message == "SteamGuardMobile") {
account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
logger.warn('Error in auth: '+account.twoFactorCode);
setTimeout(function() {
community.login(account, login);
}, 5000);
return;
}
process.exit(0);
}
logger.trace('Sucesfully auth');
account.sessionID = sessionID;
account.cookies = cookies;
community.getWebApiKey('csgobananas.com', webApiKey);
community.startConfirmationChecker(10000, account.identity_secret);
}
function webApiKey(err, key) {
if(err) {
logger.error('Cant make apikey')
logger.debug(err);
process.exit(0);
return;
}
account.key = key;
logger.trace('API key bot '+account.accountName+' '+account.key);
offersSetup();
community.loggedIn(checkLoggedIn);
}
function offersSetup() {
logger.trace('Loaded steam-tradeoffers');
offers.setup({
sessionID: account.sessionID,
webCookie: account.cookies,
APIKey: account.key
});
}
function checkLoggedIn(err, loggedIn, familyView) {
if((err) || (!loggedIn)) {
logger.error('We arent logged in')
process.exit(0);
} else {
logger.trace('Logged in');
account.auth = true;
bot_manager.js code:
var forever = require('forever-monitor');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
database: 'placeholder',
host: 'placeholder',
user: 'placeholder',
password: 'placeholder'
});
query('SELECT * FROM `bots`', function(err, row) {
if((err) || (!row.length)) {
console.log('Failed request or empty bot table');
console.log(err);
return process.exit(0);
}
console.log('List of bots:');
row.forEach(function(itm) {
console.log('Launching bot# '+itm.id);
var bot = new (forever.Monitor)('bot.js', {
args: [itm.id]
});
bot.on('start', function(process, data) {
console.log('Bot with ID '+itm.id+' started');
});
bot.on('exit:code', function(code) {
console.log('Bot stopped with code '+code);
});
bot.on('stdout', function(data) {
console.log(data);
});
bot.start();
});
});
function query(sql, callback) {
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
console.info('Database connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}
I am trying to figure out how to use Promises with the AMS Javascript API.
These are the two functions I have created that will be 'Promised'
function checkUsername(username, table) {
return table.where({username: username}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
function checkEmail(email, table) {
return table.where({email: email}).read({
success: function (results) {
if (results.length === 0) {
return true;
} else {
return false;
}
},
error: function(error) {
return false;
}
});
}
checkUsername(body.username, accountsTable).then(function (results) {
if (results) {
return checkEmail(body.email, accountsTable);
} else {
response.send(400, {message: 'This username is already in use.'});
}
}).then(function(results) {
if (results) {
response.send(200, {message: 'Can proceed with sign up.'});
} else {
response.send(400, {message: 'This email address is already in use.'});
}
});
I am trying to use the promises as I would in Parse, but it's clearly not working. The console logs keep spitting out an Internal Server Error and that .then() is not a function of the object. I'm assuming I am missing a require or something in order to have the Promises functionality?
Error in script '/api/register.js'. TypeError: Cannot call method 'done' of undefined
at exports.post (D:\home\site\wwwroot\App_Data\config\scripts\api\register.js:30:59)
[external code]
I have realized what I was doing wrong.
I have now decided to use the Q Node Module for my promises.
var q = require('q');
exports.post = function(request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var push = request.service.push;
var tables = request.service.tables;
var accountsTable = tables.getTable('Accounts');
var params = request.body;
checkUsername(params.username, accountsTable).then(function (result) {
if (result.length === 0) {
return checkEmail(params.email, accountsTable);
} else {
response.send(400, {message: 'This username is in use.'});
}
}).then(function (results) {
if (results.length === 0) {
return;
} else {
response.send(400, {message: 'This email address is already registered.'});
}
}).then(function () {
response.send(200, {message: 'Username and email are unique. You can register!'});
});
};
function checkUsername(username, table) {
var deferred = q.defer();
table.where({username: username}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
function checkEmail(email, table) {
var deferred = q.defer();
table.where({email: email}).read({
success: function (result) {
deferred.resolve(result);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}