i var undefined inside a for loop - javascript

//Server Functions
var socketArray = [];
var socketRcon = [];
for (var i = 0; i < serversConfig.serversArray.length; i++) {
socketArray[i] = new Socket;
socketArray[i].setEncoding("utf8");
socketArray[i].setNoDelay();
socketArray[i].setTimeout(1000);
socketArray[i].connect(serversConfig.serversArray[i].port, serversConfig.serversArray[i].ip);
socketRcon[i] = serversConfig.serversArray[i].rcon;
socketArray[i].on("connect", function() {
this.write(socketRcon[i] + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
socketArray[i].on("data", function(data) {
console.log(data);
});
socketArray[i].on("error", function(err) {
console.log("ERROR:" + err);
});
socketArray[i].on("close", function(err) {
console.log("CLOSED:" + err);
});
};
This is the code I have now to connect to multiple servers from a config file, and I need that each time the socket connects, I need to send a password to it. But 'socketRcon[i]' is undefined, why is that happening and how do i fix it?

Because by the time that code is run, i is equal to serversConfig.serversArray.length, meaning socketRcon[i] is undefined.
Anchor your value:
for( var i=0; i<l; i++) (function(i) {
// do stuff here
})(i);

You could also just do:
serversConfig.serversArray.forEach(function(srvconfig) {
var sock = new Socket();
sock.setEncoding("utf8");
sock.setNoDelay();
sock.setTimeout(1000);
socketArray.push(sock);
socketRcon.push(srvconfig.rcon);
sock.on("connect", function() {
this.write(srvconfig.rcon + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
sock.on("data", function(data) {
console.log(data);
});
sock.on("error", function(err) {
console.log("ERROR:" + err);
});
sock.on("close", function(err) {
console.log("CLOSED:" + err);
});
sock.connect(srvconfig.port, srvconfig.ip);
});

Related

receive and delete message in a while loop on aws

I have a code like this written in node.js for aws applications. I'm familiar with java and python but not with javascript.
I need to check if i have any messages left in my queue and if so i need to proccess them then delete. But as far as i understand the while loop doesn't wait for my queue processes and just run. After some time it exhausts my memory.
If i do it with for loop then no problem but i must do this with while loop so is there any way to use while loop for this?
message_count = true;
while (message_count === true)
{
queue.getQueueAttributes(params_queue, function (err, data)
{
if (err)
console.log(err, err.stack);
else
console.log(data);
if (data.Attributes.ApproximateNumberOfMessages == "0")
{
message_count = false;
}
queue.receiveMessage(function (err, data)
{
if (data)
{
message = data.Messages[0].Body
receipthandle = data.Messages[0].ReceiptHandle;
params.ReceiptHandle = receipthandle
queue.deleteMessage(params, function (err, data)
{
if (err)
console.log(err, err.stack);
else
console.log(data);
});
}
});
});
}
Here is some sample code I wrote sometime back to consume messages from queue. And when there are no messages try again after 1 minute delay.
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
AWS.config.update({region: 'us-east-1'});
var sqs = new AWS.SQS();
var sqsQueueURl = "<queueurl>";
var receiveMessageParams = {
QueueUrl : sqsQueueURl,
MaxNumberOfMessages : 10,
VisibilityTimeout : 10,
WaitTimeSeconds : 10
};
var receiveMessage = function() {
sqs.receiveMessage(receiveMessageParams, function(err, data) {
if(err){
console.log(err);
}
if (data.Messages) {
for (var i = 0; i < data.Messages.length; i++) {
var message = data.Messages[i];
var body = JSON.parse(message.Body);
// execute logic
removeFromQueue(message);
}
receiveMessage();
} else {
setTimeout(function() {
receiveMessage()
}, 60 * 1000);
}
});
};
var removeFromQueue = function(message) {
sqs.deleteMessage({
QueueUrl : sqsQueueURl,
ReceiptHandle : message.ReceiptHandle
}, function(err, data) {
err && console.log(err);
});
};
receiveMessage();

Why isn't my promise getting resolved?

I have two functions - A helper function for downloading files which is as follows
var downloadHelper = function(url, saveDir) {
var deferred = Q.defer();
setTimeout(function() {
deferred.resolve("success");
}, 2000);
return deferred.promise;
}
Now I have a list of files to be downloaded in parallel. I have the logic for that function as follows:
var downloadAll = function() {
var fileDownloadList = []
for(var key in config.files) {
var deferred = Q.defer();
var saveLocation = __base + config.localDir
downloadHelper(
config.files[key],
saveLocation
).then(function() {
deferred.resolve("downloaded: " + fileUrl);
}).catch(function(err) {
deferred.reject(err);
});
fileDownloadList.push(deferred.promise);
}
Q.all(fileDownloadList).done(function() {
console.log("All downloaded");
},function(err) {
console.log(err);
});
setTimeout(function() {
console.log(fileDownloadList);
}, 10000);
}
The done is never getting called!
For debugging purposes, I added a setTimeout that will be called after 10 seconds and what I see is that out of 2 files, the second promise is resolved and the first one is still in pending state.
Any ideas?
Thanks in advance
One way to make your code work
for(var key in config.files) {
(function() {
var deferred = Q.defer();
var saveLocation = __base + config.localDir
downloadHelper(
config.files[key],
saveLocation
).then(function() {
deferred.resolve("downloaded: " + fileUrl);
}).catch(function(err) {
deferred.reject(err);
});
fileDownloadList.push(deferred.promise);
}());
}
But since downloadhelper returns a promise, no need to create yet another one
for (var key in config.files) {
var saveLocation = __base + config.localDir
fileDownloadList.push(downloadHelper(
config.files[key],
saveLocation
).then(function () {
return("downloaded: " + fileUrl);
}));
}
You'll see I removed
.catch(function(err) {
deferred.reject(err);
})
That's redundant, it's the same as not having the catch at all

Parse "Unexpected identifier in main.js" in my Cloud Code

I am trying to deploy my newly written cloud code function to Parse but I keep getting the error "Unexpected identifier" at line 110, I can't seem to figure out how there is an error here, any help?
Parse.Cloud.define("backgroundJob", function(request, response) {
Parse.Cloud.useMasterKey();
var moments = require("cloud/moments.js");
var now = moments.moment();
var groupObject = Parse.Object.extend("Group");
var query = new Parse.Query(groupObject);
var eventObject = Parse.Object.extend("Event");
query.find().then(function(groups) {
var promise = Parse.Promise.as();
_.each(group, function(result) {
promise = promise.then(function() {
var count = 0;
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
var curEvent = eventArray[count];
eventArray[count].destory();
var relationc = result.get("created");
var createdq = relationc.query();
var relationj = result.get("created");
var joinedq = relationj.query();
var partOnee = curEvent.get("name");
var outString = partOnee.concat(" is now");
Parse.Push.send({
where: createdq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
Parse.Push.send({
where: joinedq,
data: {
alert: outString
}
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
}
count = count+1;
});
});
});
}).then(function() {
response.success()
}, function(error) {
response.error(error);
});
});
Line 110 is var curEvent = eventArray[count];
You missed ) in this line if (now == eventArray[count].get('date'), see:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date') {
Fix:
var events = _.map(result.get("Events"), function(eventArray) {
if (now == eventArray[count].get('date')) {
Note, when interpreters/compilers (in most programming languages) say there is a problem on a line, usually the problem can be in any row before.

Parse .each() does not work within when()

Parse.Cloud.define("bulkUpdateUserViewedTraces", function(request, response){
Parse.Cloud.useMasterKey();
var userQuery = new Parse.Query(Parse.User);
userQuery.limit(200);
var userCount = 0;
userQuery
.find(function (users) {
var promises = _.map(users, function (user){
userCount++;
return populateViewedTraces(user);
});
return promises;
})
.then(function (promises) {
return Parse.Promise.when(promises);
})
.then(function(){
console.log("Processed " + userCount + " users");
response.success("Processed " + userCount + " users");
}, function(error){
console.error(JSON.stringify(error));
response.error(error);
});
});
function populateViewedTraces (user) {
var viewedTracesCount = 0;
var viewHistoryQuery = new Parse.Query("ViewHistory");
viewHistoryQuery.equalTo("user", user);
return viewHistoryQuery
.each(function (viewHistory) {
console.log("Got here");
viewedTracesCount++;
})
.then(function () {
console.log("Got here 2");
return user.save();
});
}
Doesnt work. Logs "Processed x users" but never logs "got here". The promises should execute during the when() call, but never do.
This makes absolutely no sense as every post I've seen describing when is written like this. For some reason this just doesnt do anything.

Loop for casper.start only executed once

I got the following script to loop through a page's options to fetch subsequent values:
var casper = require('casper').create();
casper.on('remote.message', function (message) {
this.echo(message);
});
casper.on( 'page.error', function (msg, trace) {
this.echo( 'Error: ' + msg, 'ERROR' );
});
casper.start(url, function() {
this.evaluate(function() {
// nothing
});
this.then(function() {
ddlArea_options = this.getElementsAttribute('#ddlArea option', 'value');
for(var i = 0; i < ddlArea_options.length; i++) {
if(ddlArea_options[i] != '') {
this.echo(ddlArea_options[i]);
startQuery('myID', ddlArea_options[i]);
}
}
});
});
where startQuery(id, val) is a function contains casper.start():
function startQuery(id, val) {
casper.start(url, function() {
this.echo('startQuery started');
var obj = {};
obj['#' + id] = val;
this.fillSelectors('#form1', obj, true);
this.evaluate(function() {
__doPostBack('ddlArea', '');
});
this.then(function() {
this.echo("doPostback complete");
var values = this.getElementsAttribute('#anotherSelect option', 'value');
for(var i = 0; i < values.length; i++) {
this.echo(values[i]);
}
});
});
casper.run();
}
but startQuery() is executed once only, on the last item in for-loop. What did I miss?
You can only have one start-run pair per casper instance. start resets all the steps before, so everything that was in the queue is gone. In startQuery, you can change casper.start to casper.thenOpen and remove casper.run completely.

Categories