I have an array and i need process them. While task is running i need to save some information to send through ajax. I use async module, but don't do what i need.
Example:
var sendData = new Array();
async.each(mails, function(item) {
var mail = item.trim();
console.log(mail);
User.find({mail: mail},function(err, user){
if (user.length > 0) {
sendMail(mail);
var reg = new REG({mail: mail, resp:"Send Mail"});
reg.save(function(err){
if(!err){
var dat ={success: true,msg: "Seccess!"};
sendData.push(dat);
}
});
}else{
var dat ={success: false,msg: "Error!"};
sendData.push(dat);
}
});
}, function(err) {
if (err) {
console.log("ERROR");
console.log(err);
}
console.log("sendResp");
console.log(sendData);
res.send(sendData);
});
var sendData = new Array();
async.each(mails, function(item,callback) {
var mail = item.trim();
console.log(mail);
User.find({mail: mail},function(err, user){
if (user.length > 0) {
sendMail(mail);
var reg = new REG({mail: mail, resp:"Send Mail"});
reg.save(function(err){
if(!err){
var dat ={success: true,msg: "Seccess!"};
sendData.push(dat);
}
});
}else{
var dat ={success: false,msg: "Error!"};
sendData.push(dat);
}
callback();
});
}, function(err) {
if (err) {
console.log("ERROR");
console.log(err);
}
console.log("sendResp");
console.log(sendData);
res.send(sendData);
});
wish this can help u!
Related
Im consuming a JSON file and its working fine, but how can i make this a function that i can call to active?
var getDescriptionLotoFacil = function (url, callback) {
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'json';
ajax.onreadystatechange = function () {
var status = ajax.status;
if (status === 200) {
callback(status, ajax.response);
} else {
callback(null, ajax.response);
}
};
ajax.send();
};
getDescriptionLotoFacil('games.json', function (err, data) {
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
var bets = document.getElementById('bets-description');
bets.innerHTML = '';
bets.innerHTML += data.types[0].description;
}
});
just "wrap" this in a higher level function:
const myFunction = function() {
getDescriptionLotoFacil('games.json', function (err, data) {
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
var bets = document.getElementById('bets-description');
bets.innerHTML = '';
bets.innerHTML += data.types[0].description;
}
});
}
You can also use a lambda syntax instead, replace first lines by:
const myFunction = () => getDescriptionLotoFacil('games.json', function (err, data) {
...
then you call myFunction() and that executed the whole call.
I have a dropdown in which I am showing the dates:-
<label>Date:</label>
<select data-ng-model="date" name="viewDate" data-ng-options="d for d in newDates" data-ng-change="selectDate(date)" required="required">
<option value="">Please Select</option>
</select>
Directive Code:-
scope.getDates = function () {
scope.newDates = [];
ApiServices.getAllDates().then(
function (response) {
scope.dates = response.data;
scope.dates.forEach(function (entry,index) {
entry = moment(entry).format('YYYY-MM-DD');
scope.newDates.push(entry);
});
if (scope.dates.length) {
scope.noRecords = false;
} else {
scope.noRecords = true;
}
},
function (err) {
// Handle error here
console.log('Error' + JSON.stringify(err.data));
});
};
As date is coming in epoch I am trying to convert it in the human readable form. But the values are showing duplicate for each entry. I think the code I wrote for converting epoch ino string is wrong.Can anyone tell me my mistake.
Here the solution I tried and its working.No duplicate values now.
scope.getDates = function () {
scope.newDates = new Set();
ApiServices.getAllDates().then(
function (response) {
scope.dates = response.data;
scope.dates.forEach(function (entry,index) {
scope.newDates = scope.dates.map(function(entry){
entry = moment(entry).format('YYYY-MM-DD');
return entry;
});
});
if (scope.dates.length) {
scope.noRecords = false;
} else {
scope.noRecords = true;
}
},
function (err) {
// Handle error here
console.log('Error' + JSON.stringify(err.data));
});
};
If you don't want duplicated values, you can create a set instead a list.
scope.getDates = function () {
scope.newDates = new Set();
ApiServices.getAllDates().then(
function (response) {
scope.dates = response.data;
scope.dates.forEach(function (entry,index) {
entry = moment(entry, 'YYYY-MM-DD').format();
scope.newDates.add(entry);
});
if (scope.dates.length) {
scope.noRecords = false;
} else {
scope.noRecords = true;
}
},
function (err) {
// Handle error here
console.log('Error' + JSON.stringify(err.data));
});
};
scope.getDates = function () {
$scope.humanizedDates = [];
ApiServices.getAllDates().then(
function (response) {
if (response.data.length) {
$scope.humanizedDates = response.data.map(function(date){
return moment(date).format('YYYY-MM-DD');
});
scope.noRecords = false;
} else {
scope.noRecords = true;
}
},
function (err) {
// Handle error here
console.log('Error' + JSON.stringify(err.data));
});
};
im having a problem with my function Mrequest,the problem is that data like id and year are not add to de array. I know is a problem with the function but i just cant solve it.
any idea of what could i change so my array result get the ID and the YEAR
function getContent() {
var result = [];
async.series([
getDb,
getInfos
]);
function getDb(done) {
//posta
var query = "SELECT title , launch_year FROM content WHERE content_genre_id=1 && content_type_id!=2 LIMIT 2;"
mysqlConnection.query(query, function(err, data) {
result = data;
async.each(result, getPelicula, done);
});
}
function Mrequest(pagina, callback){
request({
url: pagina,
method: "GET",
json: true,
}, callback);
}
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
var pagina = "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false"
setTimeout(function() {
Mrequest(pagina, function(error, res, body) {
if (error) {
console.log("error", error);
} else {
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
console.log(pelicula);
console.log("id",id);
console.log("year",year);
console.log("year",year_solo);
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
} else {
pelicula.id = -1;
pelicula.year_pagina = null;
}
}
}
});
}, result.indexOf(pelicula) * 3000);
donePelicula();
}
getContent();
}
it doesn't look like you are making the request because getContent is being called from within itself
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();
//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);
});