Callback isn't called - javascript

I use the following code and it seems that the callback (Which start with Im HERE) is not called, any idea why?
console.log("im starting");
process.start(function() {
//this line doesnt called
console.log("im HERE");
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log(' listen to: ' + app.get('port'));
}
});
});
the method start are called and finish ...any idea what it can be ?
before ive added the process.start the code look like following:
And this works OK, now I need to add this process.start and when it finish to do the server.listen
module.exports = (function() {
server.listen(app.get('port'), function(err) {
if (err) {
console.error(err);
} else {
console.log('listen ' + app.get('port'));
}
});
}());
UPDATE
This is the code of process start
exports.start = function () {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (conf) {
require.cache.pe.configObj = conf;
}, function (err) {
console.log(err);
});
envHandler.eventE.on('AppP', function () {
console.log('User port ' + require.cache.per);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
}
I use promise lib like bluebird if its matter in this case

It's a bit unclear where you want to call the callback. In short, change the start function to accept a callback parameter and call callback() when you are done (or pass it at end as argument to then).
exports.start = function (callback) {
Validator.validateJson(function (err) {
console.log(err);
process.exit(1);
});
plugin.parse().then(function (configObj) {
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.configObj = configObj;
}, function (err) {
console.log(err);
});
envHandler.eventEmitterIns.on('AppPortDef', function () {
console.log('User port ' + require.cache.persist.port);
});
var run= function () {
return Promise.all([
childPro.create(path.join(value)),
childPro.findAndUpdateUser()
]).spread(function (cmd,updatedAppEnv) {
return Promise.all([childProc.executeChildProcess('exec', cmd, updatedAppEnv), Promise.delay(50).then(function (results) {
return inter.ProcessRun(val);
})]);
})
}();
run.then(callback);
}

Related

How to repeat part of this JS function forever every 30 seconds?

Okay, so heres the full source of my function. All I want that the part that is surrounded by "////////////" would repeat. New function works too. I could have them both, very confused once I tried to pull the highlighted function into a new one and got loads of errors.
function reWebLogOn(steam, callback) {
steam.webLogOn(function(newCookie){
helper.msg('webLogOn ok');
cookies = newCookie;
offers.setup({
sessionID: currentSessionId,
webCookie: newCookie
}, function(){
if (typeof callback == "function") {
callback();
}
});
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: config.steamid,
identity_secret: config.identitySecret,
device_id: device_id,
webCookie: newCookie,
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
}).bind(this));
}).bind(this));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
});
}
use timer's, an Interval would be handy
setInterval(function() {
//.. part that should be repleated
}, 30*1000);
window.setInterval() is your friend.
it executes a function at the provided interval of time.
for example, setInterval(()=>console.log("foo"),100) will log "foo" in the console every 100ms.
function reWebLogOn(steam, callback) {
steam.webLogOn(function(newCookie){
helper.msg('webLogOn ok');
cookies = newCookie;
offers.setup({
sessionID: currentSessionId,
webCookie: newCookie
}, function(){
if (typeof callback == "function") {
callback();
}
});
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: config.steamid,
identity_secret: config.identitySecret,
device_id: device_id,
webCookie: newCookie,
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
setInterval((function(){
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations){
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
}).bind(this));
}).bind(this));
}).bind(this),30000)
Put your code inside setInterval(function(){},1000) timer or do some recursive calls.

Callback is not a function in mongoose.find({})

I am new to Node.js and mongoose, i am trying to query objects from a mongo collection using find({}) and the function is as follows :
schema.statics.listAllQuizes = function listAllQuizes(){
Model.find({},function(err,quizes,cb){
if(err){
return cb(err);
}else if(!quizes){
return cb();
}
else {
return cb(err,quizes);
}
});};
But when i call this function i get an error saying
return cb(err,quizes);
^
TypeError: cb is not a function
I am stuck at this point, can someone please help me with this, thanks in advance.
The callback should an argument to listAllQuizes, not an argument to the anonymous handler function.
In other words:
schema.statics.listAllQuizes = function listAllQuizes(cb) {
Model.find({}, function(err, quizes) {
if (err) {
return cb(err);
} else if (! quizes) {
return cb();
} else {
return cb(err, quizes);
}
});
};
Which, logically, is almost the same as this:
schema.statics.listAllQuizes = function listAllQuizes(cb) {
Model.find({}, cb);
};
Here's an example on how to use it:
var quiz = App.model('quiz');
function home(req, res) {
quiz.listAllQuizes(function(err, quizes) {
if (err) return res.sendStatus(500);
for (var i = 0; i < quizes.length; i++) {
console.log(quizes[i].quizName)
}
res.render('quiz', { quizList : quizes });
});
}
Assuming you have code somewhere that looks like this:
foo.listAllQuizzes(function (err, quizzes) {
...
});
Then your function listAllQuizzes is passed a callback:
schema.statics.listAllQuizzes = function (cb) {
Model.find({}, function(err, quizzes) {
if (err) return cb(err);
cb(null, quizzes);
});
};

Calling async function befrore server start to listen

I've node app and I want to call to function before the server is start,my questions are:
what is the recommended why to do it ?
does that can have an issue (that I call to some async function before the server is up)
Btw I use bluebird
This is my code
//This is the function which I want to call before
process.beforeProc();
//Before I start the following server
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
**UPDATE**
The preProcess look like following
exports.beforeProc= function () {
run.validate(function (err) {
console.log(err);
process.exit(1);
});
Parser.parse().then(function (con) {
//Cache the path values to serve new requests
if (typeof require.cache.persist === 'undefined') {
require.cache.persist = {};
}
require.cache.persist.con = con;
}, function (err) {
console.log(err);
});
.....
I don't have 50 rep so I made an answer:
Does process.beforeProc() have a callback?
If so you can do it like this:
process.beforeProc(function() {
// Once the beforeProc loaded it will return the callback, so whats
// in here
http.createServer(app).listen(app.get('port'), function (err) {
if (err) {
console.error(err);
} else {
console.log('listening on port ' + app.get('port'));
}
});
});

Async confusion in node.js

I'm in deep trouble trying to understand how to make my code asynchronous in Node.js land. Please see my code below, in two varieties.
Ok so here's my first try - I have three functions here. A processing function (iim), a file copy function (fse.copy), and an archive function (da).
I need da to happen after iim, and iim to happen after fse.copy.
This first approach results in archive happening, but it's empty because iim never appears to happen.
da(randomString, function(err) {
if (err) {
log.error(err);
} else {
fse.copy(temp_path, new_location + file_name, function(err) {
if (err) {
log.error(err);
} else {
log.info("File saved to " + new_location + file_name);
var sourceImage = new_location + file_name;
log.debug(sourceImage);
log.debug(randomString);
iim(sourceImage, randomString, function(err) {
if (err) {
log.error(err);
}
});
}
});
}
});
The next block is an alternate approach which results in the da happening before iim is finished.
fse.copy(temp_path, new_location + file_name, function(err) {
if (err) {
log.error(err);
} else {
log.info("File saved to " + new_location + file_name);
var sourceImage = new_location + file_name;
log.debug(sourceImage);
log.debug(randomString);
iim(sourceImage, randomString, function(err) {
if (err) {
log.error(err);
}
});
da(randomString, function(err) {
if (err) {
log.error(err);
}
});
}
});
Here's what I'd recommend -- in your question you say you need to essentially run three functions in series -- correct? Run function A, then function B, and lastly, run function C.
The simplest way to do this is using the asyncjs library.
Here's an example:
var async = require('async');
async.series([
function a(cb) {
// do stuff
cb();
},
function b(cb) {
// do stuff
cb();
},
function c(cb) {
// do stuff
cb();
},
], function() {
// this will run once all three functions above have finished
});
Now, let's say that each of those functions needs to return data to the next function. SO imagine that function B needs input from function A to run. How do you accomplish that? Using async.waterfall!
var async = require('async');
async.waterfall([
function a(cb) {
// do stuff
cb(null, 'value');
},
function b(val, cb) {
// do stuff with val
cb(null, 'woot');
},
function c(val, cb) {
// do stuff with val
cb(null);
},
], function() {
// this will run once all three functions above have finished
});
Not bad right?
Hope this helps!
EDIT: Here's a code block showing your code above refactored using asyncjs:
async.waterfall([
function(cb) {
fse.copy(temp_path, new_location + file_name, function(err) {
if (err) {
log.error(err);
} else {
log.info("File saved to " + new_location + file_name);
var sourceImage = new_location + file_name;
log.debug(sourceImage);
log.debug(randomString);
}
console.log('Finished running fs.copy');
cb(null, sourceImage, randomString);
});
},
function(sourceImage, randomString, cb) {
iim(sourceImage, randomString, function(err) {
if (err) {
log.error(err);
}
console.log('Finished running iim');
cb(null, randomString);
});
},
function(randomString, cb) {
da(randomString, function(err) {
if (err) {
log.error(err);
}
console.log('Finished running da');
cb();
});
}
], function() {
console.log('All done!');
});
So you can either put da into the callback for iim (right now it's not) from your second example:
fse.copy(temp_path, new_location + file_name, function(err) {
if (err) {
log.error(err);
} else {
log.info("File saved to " + new_location + file_name);
var sourceImage = new_location + file_name;
log.debug(sourceImage);
log.debug(randomString);
iim(sourceImage, randomString, function(err) {
if (err) {
log.error(err);
return;
}
da(randomString, function(err) {
if (err) {
log.error(err);
}
});
});
}
});
That said, callback depth can be flattened with the use of a library like async (https://github.com/caolan/async)

Uploading to dropbox via node js fails

I have the following code to read from a stream and upload to Dropbox. But I'm getting a
Uncaught TypeError: Cannot call method 'toString' of undefined
at Function.Dropbox.Util.Xhr.Xhr.urlEncodeValue (node_modules\dropbox\lib\dropbox.js:3695:40)
at Function.Dropbox.Util.Xhr.Xhr.urlEncode (node_modules\dropbox\lib\dropbox.js:3689:59)
at Xhr.Dropbox.Util.Xhr.Xhr.paramsToUrl (node_modules\dropbox\lib\dropbox.js:3570:40)
at Xhr.Dropbox.Util.Xhr.Xhr.prepare (node_modules\dropbox\lib\dropbox.js:3598:14)
at Client.Dropbox.Client.Client._dispatchXhr (node_modules\dropbox\lib\dropbox.js:2137:11)
at Client.Dropbox.Client.Client.resumableUploadStep (node_modules\dropbox\lib\dropbox.js:1454:19)
.....
error when I try to run the code.If I give a 'false' as cursor, the error doesn't occur in step function, but still it occures in finish function. Can anyone help me on this?
stream.on('data', function (data) {
client.resumableUploadStep(data, function (error, cursor) {
if (error) {
return console.log(error);
}
})
});
stream.on('end', function () {
client.resumableUploadFinish(fileName, function (error, stats) {
if (error) {
return callback(error);
}
return callback(null, stats);
});
});
I used the following code and now it works.
var pcursor = null;
var eventObject = new EventEmitter();
var counter = 0;
stream.on('data', function (data) {
counter++;
client.resumableUploadStep(data, pcursor, function (error, cursor) {
if (error) {
return callback(error);
}
counter--;
pcursor = cursor;
eventObject.emit('event');
});
});
stream.on('end', function () {
eventObject.on('event', function () {
if (counter == 0) {
client.resumableUploadFinish(fileName, pcursor, function (error, stats) {
if (error) {
return callback(error);
}
return callback(null, stats);
});
counter = -1;
}
});
eventObject.emit('event');
});
It looks like you're missing the cursor parameter to resumableUploadFinish. Also, you should be passing in a cursor to resumableUploadStep after the first call too.
I think the code you want is something like this (completely untested):
var cursor = null;
stream.on('data', function (data) {
client.resumableUploadStep(data, cursor, function (error, new_cursor) {
cursor = new_cursor;
});
});
stream.on('end', function () {
client.resumableUploadFinish(fileName, cursor, function (error, stats) {
return callback(null, stats);
});
});

Categories