return results from a function (javascript, nodejs) - javascript

Could anyone help me with this code? I need to return a value form a routeToRoom function:
var sys = require('sys');
function routeToRoom(userId, passw) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, (function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
}
));
});
return roomId;
}
sys.puts(routeToRoom("alex", "123"));
But I get always: 0
I guess return roomId; is executed before roomId=results.creationix.room. Could someone help me with this code?

function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts is deprecated

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.
As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.
Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Related

Express dosn't get return of other function querying Mongodb [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm working in a simple API Key authentication, I just want to verify the given key against the user provied key.
I have a seperate file with the function querying the database, and returning true/false and the user object.
But in my route.js file, the return object is undefined even tough in my auth.js file it isn't.
I tried making the the function in router.get an async function using express-promise-router and making the function an await return var user = await auth.verify(req.params.uid, req.get("token")) but I don't realy know how async works.
router.js
[...]
router.get('/list/:uid', function(req, res) {
var user = auth.verify(req.params.uid, req.get("token"))
console.log("User: " + user) // <-- Undefined
if (user.status) {
res.send("Success")
} else {
res.status(403)
res.json({status: 403, error: "Unkown User / Token"})
}
})
[...]
auth.js
var db = require('./db')
var ObjectId = require('mongodb').ObjectId;
module.exports = {
verify: (uid, key) => {
try {
var collection = db.get().collection('users')
const obj_id = new ObjectId(uid)
const query = { _id: obj_id }
collection.find(query).limit(1).toArray(function(err, user) {
var status = 0;
var usr = {};
if (err) {throw err}else{status=1}
if (user.length <= 0) {throw "NotExistingExc"; status = 0}else{
usr = user[0];
if (key != usr.api) status = 0
}
var returnObj = {
status: status,
user: usr
} /* --> Is {
status: 1,
user: {
_id: d47a2b30b3d2770606942bf0,
name: 'Sh4dow',
groups: [ 0 ],
api: 'YWFiMDI1MGE4NjAyZTg0MWE3N2U0M2I1NzEzZGE1YjE='
}
}
*/
return returnObj;
})
} catch (e) {
console.error(e)
return {
status: 0,
user: {},
error: e
}
}
}
}
db.js (Idk if needed)
var MongoClient = require('mongodb').MongoClient
var state = {
db: null,
}
exports.connect = function(url, done) {
if (state.db) return done()
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) return done(err)
state.db = db
done()
})
}
exports.get = function() {
return state.db.db("database")
}
exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null
state.mode = null
done(err)
})
}
}
I want to have the returnObjin auth.js in the router.get of my route.js file.
Make auth.verify return a Promise which we can then await for it inside router, You can just make the callback async no need for express-promise-router
router.get('/list/:uid', async function(req, res) {
try {
var user = await auth.verify(req.params.uid, req.get("token"))
console.log("User: " + user)
if (user.status) {
res.send("Success")
} else {
res.status(403).json({status: 403, error: "Unkown User / Token"})
}
} catch (e) {
console.error(e)
res.status(/* */).json(/* */)
}
})
auth
module.exports = {
verify: (uid, key) => new Promise((resolve, reject) => {
var collection = db.get().collection('users')
const obj_id = new ObjectId(uid)
const query = { _id: obj_id }
collection.find(query).limit(1).toArray(function(err, user) {
var status = 0;
var usr = {};
if (err) {
reject(err)
return
} else {
status = 1
}
if (user.length <= 0) {
reject(new Error("NotExistingExc"))
return
} else {
usr = user[0]
if (key != usr.api) status = 0
}
var returnObj = {
status: status,
user: usr
}
resolve(returnObj);
})
}
}
In short, the reason you get undefined is because the code in auth.js is asyncronous. But you're really close. The toArray method in MongoDB returns a promise, so you need to make sure you return that promise and then use it in the router correctly.
In auth.js, make sure verify returns a promise - just add return!
return collection.find(query).limit(1).toArray(...)
And then, change your usage of the verify to the async/await you originally tried:
router.get('/list/:uid', async function(req, res) {
var user = await auth.verify(req.params.uid, req.get("token"))
// More code here...
})

mongoose js won't print out query value

I want to create using mongoose js a collection of kitten with this document in it {name: "mike"}.
After creating this document I want to print it's value.
I wrote this code below.
2 problems:
this code doesn't end (meaning when I wrote node file.js the cmd line stays open (stucked) and no return value is return (infinite loop like in a server).
the code doesn't print the value of "mike". just create this doucument...
what am I doing wrong?
thanks
var mongoose = require('mongoose');
var url = 'mongodb://Yotam:Yotam#ds023475.mlab.com:23475/small-talkz';
mongoose.connect(url);
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('kitten', kittySchema);
Kitten.create({ name: "mike" }, function (err, small) {
if (err) return handleError(err);
});
Kitten.findOne( { } ), function(err, docs){
console.log(docs.name);
};
return 1;
newKitten = { name: "mike" };
Kitten.create(newKitten, function (err, kitty) {
if {
(err) return handleError(err);
} else {
console.log(kitty); //OR console.log(kitty.name);
}
});
Kitten.findOne({name: "mike"}).exec(function(e, kitten) {
if (e) {
console.log(e)
} else {
console.log(kitten.name)
}
});
the problem was {for anyone whose intersted (and thanks for herkou)} that I did not use the exec command..
This works:
Kitten.findOne( { name: "mike"} ).exec( function(err, docs){
console.log(docs.name);
return;
});
update:
also had a probelm with race conditions... the create of the documnet not finished when the query was called. that is why I got undeinfed.
use this new code:
var mongoose = require('mongoose');
var url = 'mongodb://Yotam:Yotam#ds023475.mlab.com:23475/small-talkz';
mongoose.connect(url);
var kittySchema = mongoose.Schema({
name: String,
color:String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var newKitten = { name: "mike", color:"white" };
Kitten.create(newKitten, function (err, kitty) {
if (err) {
return handleError(err);
} else {
call_query();
}
});
var call_query= function(){
var query= Kitten.findOne( { name: "mike"} );
query.exec( function(err, docs){
console.log(docs.color);
return;
});
}
return 1;
now I just need to understand why this script doesn't end.

Make multiple callbacks from node js asynchronous function

How can I return a object of data returned by asynchronous function called multiple times from within a asynchronous function.
I'm trying to implement like this :
var figlet = require('figlet');
function art(dataToArt, callback)
{
var arry[];
figlet(dataToArt, function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return callback('');
}
arry[0] = data;
callback(arry);
});
figlet(dataToArt, function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return callback('');
}
arry[1] = data;
callback(arry);
});
}
art('Hello World', function (data){
console.log(data);
});
How can I do it correctly, I searched and searched but couldn't find a solution.
Ps. I'm using Figlet.js
I don't know if you're ok using an external module, but you can use tiptoe.
Install it using npm install tiptoe like any regular module and it basically goes like this:
var tiptoe = require('tiptoe')
function someAsyncFunction(obj, callback) {
// something something
callback(null, processedData);
}
tiptoe(
function() {
var self = this;
var arr = ['there', 'are', 'some', 'items', 'here'];
arr.forEach(function(item) {
someAsyncFunction(item, self.parallel());
});
},
function() {
var data = Array.prototype.slice.call(arguments);
doSomethingWithData(data, this);
},
function(err) {
if (err) throw (err);
console.log('all done.');
}
);
the someAsyncFunction() is the async function you want to call does something and calls the callback parameter as a function with the parameters error and data. The data parameter will get passed as an array item to the following function on the tiptoe flow.
Did it Myself :) Thanks to mostafa-samir's post
var figlet = require('figlet');
function WaterfallOver(list, iterator, callback) {
var nextItemIndex = 1;
function report() {
nextItemIndex++;
if(nextItemIndex === list.length)
callback();
else
iterator([list[0],list[nextItemIndex]], report);
}
iterator([list[0],list[1]], report);
}
var FinalResult = [];
WaterfallOver(["hello","Standard","Ghost"], function(path, report) {
figlet.text(path[0], { font: path[1] }, function(err, data) {
if (err) {
FinalResult.push("Font name error try help");
report();
return;
}
data = '<pre>.\n' + data + '</pre>';
FinalResult.push(data);
report();
});
}, function() {
console.log(FinalResult[0]);
console.log(FinalResult[1]);
});

Mock promises with jasmine

I've been struggling with a simple test that involves mocking promises with no luck. I'm using jasmine spies. Hope somebody can help me. I've successfully mocked findByUserName method but there appears to be something wrong with the promise. The tests just fails without any error. Please see my code:
Module CertificationSettingsManager.FindUser being tested:
'use strict';
var CertificationSettingsManagerFindUser = function(usersRepository, accountsRepository, userName, next) {
if (userName) {
usersRepository.findByUserName(userName)
.then(function(user) {
if (user && user.password) {
delete user.password;
}
return user;
})
.then(function(user) {
if (user) {
accountsRepository.findAllAssignedTo(user.userId).then(function(results) {
user.hasAccountsAssigned = (results.count > 0);
user.belongsRepHierarchy = true;
user.isMemberOfReconOrPrep = true;
next(null, user);
});
}
})
.catch(function(err) {
if (err) {
next(err);
}
});
} else {
next();
}
};
module.exports = CertificationSettingsManagerFindUser;
And this is the test spec:
'use strict';
var findUserModule = require('./CertificationSettingsManager.FindUser');
var Q = require('q');
describe('CertificationSettingsManager findUser module', function() {
var userSpy;
var accounstSpy;
var nextCallbackSpy;
var inputUserTemplate;
var accountsResult;
beforeEach(function() {
inputUserTemplate = {
userId: 1234
};
accountsResult = {
count: 0
};
userSpy = jasmine.createSpyObj('UserRepository', ['findByUserName']);
accounstSpy = jasmine.createSpyObj('ProfileRepository', ['findAllAssignedTo']);
nextCallbackSpy = jasmine.createSpy('nextCallback spy');
});
it('when userName was not supplied it should call next with no parameters', function() {
findUserModule(null, null, null, nextCallbackSpy);
expect(nextCallbackSpy).toHaveBeenCalledWith();
});
//done callback passed so it can be asynchronous
it('if user has password, it should remove the password', function(done) {
inputUserTemplate.password = 'there is some password here';
accounstSpy.findAllAssignedTo.and.returnValue(Q.resolve(accountsResult));
userSpy.findByUserName.and.returnValue(Q.resolve(inputUserTemplate));
findUserModule(userSpy, accounstSpy, 'rassiel', function(){
expect(inputUserTemplate.password).toBeUndefined();
// done being called
done();
});
});
});
The second test: it('if user has password, it should remove the password' is failing, but when I try to debug the test it never hits the then inside:
usersRepository.findByUserName(userName)
.then(function(user) {
**UPDATED!!!****
After adding the done callback to the it method, the test is working now... that's what I was missing. Then done should be called after the expects statements.
Is there a better way of doing this?

Sending emails from node server fails when using forever

I have an API server running with Node and the following add user function:
add: function (userArray, onSuccess, onError) {
userArray.forEach(function (user) {
var length = 8,
charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
var password = retVal;
var salt = bcrypt.genSaltSync(10);
var password = bcrypt.hashSync(password, salt);
user.user_type_id = user.user_type.id;
if (user.title) {
user.title_id = user.title.id;
}
user.division_id = user.division.id;
user.password = password;
user.user_password = retVal;
user.image_path = 'img/AdamProfil.png';
});
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
} else {
var transportBatch = nodemailer.createTransport(smtpTransport({
host: 'smtp.mail.dk',
secureConnection: true,
port: 587,
tls: {
rejectUnauthorized: false
},
auth: {
user: 'my#mail.com',
pass: 'myPassword'
}
}));
var Render = function(locals) {
this.locals = locals;
this.send = function(err, html, text) {
if (err) {
console.log(err);
} else {
transportBatch.sendMail({
from: '*** <support#mymail.dk>',
to: locals.username,
subject: 'Din adgangskode til ***!',
html: html,
// generateTextFromHTML: true,
text: text
}, function(err, responseStatus) {
if (err) {
console.log(err);
} else {
console.log(responseStatus.message);
}
});
}
};
this.batch = function(batch) {
batch(this.locals, templatesDir, this.send);
};
};
// Send multiple emails
template('password', true, function(err, batch) {
for(var user in userArray) {
var render = new Render(userArray[user]);
render.batch(batch);
}
});
}
});
userArray.forEach(function(user){
User.create(user)
.then(function(createdUser) {
user.profile.user_id = createdUser[null];
Profile.create(user.profile);
});
});
onSuccess(userArray);
}
Now when i run my server.js file using the console writing node server.js and run this function it correctly sends an email to the target (SUCCESS!?) no because when i run this with forever start server.js and run the exact same function with the exact same parameters no email is sent.
What the hell is going on?:)
Looking at your code only, I see a templatesDir variable. I'd guess that is different, or changing in an unexpected way, when you run with forever.
Check out this issue at forever. Do you ever reference an absolute path, or process.cwd()?
Worth a try, good luck!

Categories