How can i make this function to restart itself? - node.js

I have a Discord BOT written with Node.JS using Discord.JS
There i have a function that starts when the bot becomes online
It consists in getting an array from an API: https://jacob.rede-epic.com/api/upcomingEvents
With the timestamp, it is supposed to send a message 10, 5 and 1 minute before it happens, when it happens (Exact hour + 15 minutes, e.g: 08:15/09:15/10:15 etc), and when it finishes (20 minutes later, e.g: 08:35/09:35/10:35 etc)
How can i make it to reset the whole system ?
Code:
const { MessageEmbed } = require('discord.js');
const axios = require('axios');
class Jacob {
constructor(client) {
this.client = client;
}
async start() {
const jacobContestsChannel = this.client.channels.cache.get('852596632591269968');
let nextEventObject = null;
let sentNotification = false;
let sentNotification2 = false;
let sentNotification3 = false;
let sentNotificationActive = false;
let sentNotificationFinished = false;
const cropNames = [
'Cactus',
'Carrot',
'Cocoa beans',
'Melon',
'Mushroom',
'Nether wart',
'Potato',
'Pumpkin',
'Sugar cane',
'Wheat',
];
setInterval(async () => {
let upcomingEvents = [];
let response = await axios.get('https://jacob.rede-epic.com/api/upcomingEvents');
let request = response.data;
for (let i in request) {
upcomingEvents.push(request[i]);
}
if (nextEventObject == null) {
nextEventObject = upcomingEvents[0];
} else {
let diff = nextEventObject.timestamp - Date.now();
let active = diff < 0;
setInterval(() => {
try {
diff = nextEventObject.timestamp - Date.now();
} catch {
nextEventObject = null;
}
}, 1000);
if (diff < -20 * 60 * 1000) {
sentNotification = false;
sentNotification2 = false;
sentNotification3 = false;
sentNotificationActive = false;
nextEventObject == null;
if (!sentNotificationFinished) {
jacobContestsChannel.send(new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('The current contest has ended!')
);
sentNotificationFinished = true;
}
} else if (!active && diff < 10 * 60 * 1000 && !sentNotification) {
jacobContestsChannel.send(new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('A contest is starting in 10 minutes')
.setDescription(`Crops: ${nextEventObject.crops.map(crop => cropNames[crop]).join(', ')}`)
);
sentNotification = true;
} else if (!active && diff < 5 * 60 * 1000 && sentNotification && !sentNotification2) {
jacobContestsChannel.send(new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('A contest is starting in 5 minutes')
.setDescription(`Crops: ${nextEventObject.crops.map(crop => cropNames[crop]).join(', ')}`)
);
sentNotification2 = true;
} else if (!active && diff < 60 * 1000 && sentNotification && sentNotification2 && !sentNotification3) {
jacobContestsChannel.send(new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('A contest is starting in 1 minute')
.setDescription(`Crops: ${nextEventObject.crops.map(crop => cropNames[crop]).join(', ')}`)
);
sentNotification3 = true;
} else if (active && !sentNotificationActive) {
jacobContestsChannel.send(new MessageEmbed()
.setColor(this.client.embedColor)
.setTitle('A contest has started!')
.setDescription(`Crops: ${nextEventObject.crops.map(crop => cropNames[crop]).join(', ')}`)
);
sentNotificationActive = true;
}
console.clear();
console.log(nextEventObject);
console.log(`Diff: ${diff}`);
console.log(`Active: ${active}`);
console.log(`Notification: ${sentNotification}`);
console.log(`Notification Active: ${sentNotificationActive}`);
console.log(`Notification Finished: ${sentNotificationFinished}`);
}
}, 1000);
}
async requestUpcomingEvents() {
let response = await axios.get('https://jacob.rede-epic.com/api/upcomingEvents');
return response.data;
}
}
module.exports = Jacob;

Related

Firestore Batch write : 500 maximum writes exceeded

I'm using batch write in order to avoid 500 maximum writes limit. Even if I'm using batchArray in order to process more than 500 writes, I get this error:
Exception from a finished function: Error: 3 INVALID_ARGUMENT: maximum 500 writes allowed per request
Code: https://controlc.com/3c3a59be
exports.checkSchedine2 = functions.pubsub
.schedule('15,45 * * * *')
.onRun(async (context) => {
const batch = firestore.batch();
var currentTime = Math.floor(Date.now() / 1000);
const risultati = await firestore.collection("Risultati").doc("risultati").get();
const ref1 = await firestore.collection("Schedine").get();
let batchArray = [];
batchArray.push(batch);
let operationCounter = 0;
let batchIndex = 0;
let _notcommit = false;
await Promise.all(ref1.docs.map(async (doc) => {
const ref2 = await firestore.collection("Schedine").doc(doc.id).collection("in corso").get();
for (const doc2 of ref2.docs) {
const documentData = doc2.data();
for (matchId in doc2.data()["Match"]) {
try {
for (id in risultati.data()) {
if (matchId == id && risultati.data()[id]["status"] != 0 && doc2.data()["Match"][matchId]["status"] == 0) {
if ((doc2.data()["Match"][matchId]["Bet"] == 1 || doc2.data()["Match"][matchId]["Bet"] == 2 || doc2.data()["Match"][matchId]["Bet"] == 3) && doc2.data()["Match"][matchId]["Bet"] == risultati.data()[id].ris) {
documentData["Match"][matchId]["status"] = 1;
} else if (doc2.data()["Match"][matchId]["Bet"] == 4 && risultati.data()[id].goal == 1) {
documentData["Match"][matchId]["status"] = 1;
} else if (doc2.data()["Match"][matchId]["Bet"] == 5 && risultati.data()[id].goal == 0) {
documentData["Match"][matchId]["status"] = 1;
} else if (doc2.data()["Match"][matchId]["Bet"] == 6 && risultati.data()[id].over == 1) {
documentData["Match"][matchId]["status"] = 1;
} else if (doc2.data()["Match"][matchId]["Bet"] == 7 && risultati.data()[id].over == 0) {
documentData["Match"][matchId]["status"] = 1;
} else {
documentData["Match"][matchId]["status"] = 2;
}
}
}
} catch (e) {}
}
if (_notcommit == false) {
await batchArray[batchIndex].update(doc2.ref, documentData);
operationCounter++;
if (operationCounter > 100) {
batchArray.push(batch);
batchIndex++;
operationCounter = 0;
}
}
};
}));
Promise.all(batchArray.map(batch => batch.commit()));
});
It seems that the code launches too many commits, isn't it?
You are pushing the same batch in that batchArray in every iteration. You should be creating a new batch for every 500 operations:
let batchArray = [firestore.batch()];
// ...
if (operationCounter > 100) {
const newBatch = firestore.batch();
batchArray.push(newBatch);
batchIndex++;
operationCounter = 0;
}

How can I make my leaderboard command sorted from highest to lowest on discord.js?

This is my current code:
function leaderboardembed() {
const filtered = client.points.filter(p => p.guild === message.guild.id).array();
let orilent;
const sorted = filtered.sort((a, b) => b.vouches - a.vouches );
let embeds = [];
let j = 0;
let first = (10)
let maxnum = 50;
orilent = sorted.length;
if(isNaN(maxnum)) {
console.log("maximum_leaderboard NOT A NUMBER")
maxnum = 50;}
if (maxnum > sorted.length)
maxnum = sorted.length + (10 - Number(String(sorted.length/10).slice(2)));
if (maxnum < 10) maxnum = 10;
for (let i = 10; i <= maxnum; i += 10) {
const top = sorted.splice(0, 10);
const embed = new Discord.MessageEmbed()
.setTitle(`\`${message.guild.name}\` | Leaderboard`)
.setTimestamp()
.setDescription(`Top ${i<orilent?i:orilent}/${orilent} Ranking:`)
.setColor(embedcolor);
for (const data of top) {
j++;
try {
embed.addField(`**${j}**. \`${data.usertag}\``, ` | **Vouches:** \`${data.vouch}\``);
} catch {
embed.addField(`**${j}**. \`${data.usertag}\``, ` | **Vouches:** \`${data.vouch}\``);
}
}
embeds.push(embed);
}
return embeds;
}
async function leaderboard() {
let currentPage = 0;
const embeds = leaderboardembed();
if (embeds.length == 1)
return message.channel.send(embeds[0]).catch(e=>console.log("ranking: " + e))
const lbembed = await message.channel.send(
`**Current Page - ${currentPage + 1}/${embeds.length}**`,
embeds[currentPage]).catch(e=>console.log("ranking: " + e));
try {
await lbembed.react("⏪");
await lbembed.react("⏹");
await lbembed.react("⏩");
} catch (error) {
console.error(error);
}
const filter = (reaction, user) => ["⏪", "⏹", "⏩"].includes(reaction.emoji.name) && message.author.id === user.id;
const collector = lbembed.createReactionCollector(filter, {
time: 60000
});
collector.on("collect", async (reaction, user) => {
try {
if (reaction.emoji.name === "⏩") {
if (currentPage < embeds.length - 1) {
currentPage++;
lbembed.edit(`**Current Page - ${currentPage + 1}/${embeds.length}**`, embeds[currentPage]);
}
} else if (reaction.emoji.name === "⏪") {
if (currentPage !== 0) {
--currentPage;
lbembed.edit(`**Current Page - ${currentPage + 1}/${embeds.length}**`, embeds[currentPage]);
}
} else {
collector.stop();
reaction.message.reactions.removeAll();
}
await reaction.users.remove(message.author.id);
} catch (error) {
console.error(error);
}
});
}
This is how it displays when doing the command
The problem is that there's about 1000 members and some don't have the "vouches" and id rather just display the people that have the highest to lowest.
Here's an example of what I'm aiming it to be like:
Firstly, to sort all of them, you do need them all in an array. Otherwise, it will be excessively difficult. Here is a simple sort function that JavaScript provides for us:
var ranks = [7, 2, 9, 5, 10, 110]
ranks.sort() //don’t use this, this would put 10, 110, 2 etc since it’s alphabetical, you need to specify how to sort it
ranks.sort((a, b)=> a - b) //2, 5, 7, 9, 10, 110
//to reverse that
ranks.sort((a, b) => b-a)

Loop is not waiting for query to be executed in node js

I am using node-querybuilder module for executing queries. I need to loop query in loop.
dbConfig.getDB() returns connection and why loop is not waiting for the query to execute
firstHalf and secondHalf always A and A..loop is not waiting for query to be executed.
I am very new to node-querybuilder module.using async and await doesn't make any difference
dbConfig.getDB().query(`SELECT id, full_name, email,mobile from frms WHERE status = ? AND email IS NOT NULL`, ['1'], async (err, response) => {
if (err) {
console.log(err);
}
else if (response && response.length > 0) {
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay() - 6));
var weekArr = [firstday];
for (let j = 1; j < 6; j++) {
var nextday = new Date(curr.setDate(firstday.getDate() + j));
weekArr.push(nextday);
}
// console.log(weekArr);
let dayWiseAttendanceArr = [];
for (let i = 0; i < response.length; i++) {
let frmWiseObj = {};
frmWiseObj.basic_details = { "id": response[i].id, "name": response[i].full_name, "email": response[i].email, "mobile": response[i].mobile };
frmWiseObj.attendance_details = [];
for (let k = 0; k < weekArr.length; k++) {
let inDate = weekArr[k].toISOString().split('T')[0];
let dateWiseObj = {};
dateWiseObj.date = inDate;
let firstHalf = "A";
let secondHalf = "A";
let query = `SELECT DATE_FORMAT(in_date,'%Y-%m-%d') as date,ifnull(in_date,'') as punch_in,ifnull(out_date,'') as punch_out FROM punching_detail where DATE_FORMAT(in_date,'%Y-%m-%d') = '${inDate}' and punching_detail.frm_id='${response[i].id}'`;
dbConfig.getDB().query(query, async (punch_err, punch_response) => {
if (punch_err) {
console.log(punch_err);
} else if (punch_response && punch_response.length > 0) {
let punch_in = punch_response[0].punch_in;
let punch_out = punch_response[0].punch_out;
if (punch_in <= (inDate + " 10:40:00") && punch_out >= (inDate + " 19:00:00")) {
firstHalf = "P";
secondHalf = "P";
} else if (punch_in <= (inDate + " 10:40:00") && punch_out <= (inDate + " 19:00:00") && punch_out >= (inDate + " 14:30:00")) {
firstHalf = "P";
secondHalf = "A";
} else if (punch_in >= (inDate + " 10:40:00") && punch_in <= (inDate + " 14:30:00") && punch_out >= (inDate + " 19:00:00")) {
firstHalf = "A";
secondHalf = "P";
} else if (punch_in >= (inDate + " 10:40:00") && punch_in <= (inDate + " 14:30:00") && punch_in <= (inDate + " 19:00:00")) {
var hours = Math.abs(punch_out - punch_in) / (60 * 60 * 1000);
if (hours >= 4.5) {
firstHalf = "P";
secondHalf = "A";
} else {
firstHalf = "P";
secondHalf = "P";
}
} else {
firstHalf = "A";
secondHalf = "A";
}
} else {
let query = `SELECT leave_type,start_day, end_day,DATE_FORMAT(start_date,'%Y-%m-%d') as date,DATE_FORMAT(end_date,'%Y-%m-%d') as end_date FROM leave_mgt where (DATE_FORMAT(end_date,'%Y-%m-%d') <= '${inDate}}' AND DATE_FORMAT(start_date,'%Y-%m-%d') <= '${inDate}}') and frm_id='${response[i].id}' and status = '1'`;
await dbConfig.getDB().query(query, async (leave_err, leave_response) => {
if (leave_err) {
console.log(leave_err);
} else if (leave_response && leave_response.length > 0) {
const element = leave_response[0];
if (element.end_date != '0000-00-00') {
if (element.start_date == inDate) {
if (element.start_day == 2) {
firstHalf = 'L';
secondHalf = 'L';
} else if (element.start_day == 0) {
firstHalf = 'L';
} else if (element.start_day == 1) {
secondHalf = 'L';
}
} else if (element.end_date == inDate) {
if (element.end_day == 2) {
firstHalf = 'L';
secondHalf = 'L';
} else if (element.end_day == 0) {
firstHalf = 'L';
} else if (element.end_day == 1) {
secondHalf = 'L';
}
} else {
firstHalf = 'L';
secondHalf = 'L';
}
}
}
});
}
dateWiseObj.first_half = firstHalf;
dateWiseObj.second_half = secondHalf;
frmWiseObj.attendance_details.push(dateWiseObj);
});
}
dayWiseAttendanceArr.push(frmWiseObj);
}
}
else {
console.log("No Active frms found");
}
});
}```
Am not familiar with node-querybuilder but on this line:
await dbConfig.getDB().query(query, async (leave_err, leave_response) => {/* some code */ });
since the query method takes in a callback, it probably does not return a promise (you could confirm this by looking at the documentation/source code). This means using await here will not make your code wait for query to complete (since await has to be followed by a promise for it to have any effect).
If the library you're using doesn't use promises, maybe try promisifying the query method, so that you can await it. Promisifying can be done using something built-in like util/promisify or manually by creating a wrapper function (something like below):
function queryAsPromise(sql, parameters) {
return new Promise((resolve, reject) => {
dbConfig.getDB().query(sql, parameters, (err, response) => {
if (err) {
return reject(err);
}
resolve(response);
});
});
}
You can then await whatever queryAsPromise resolves to, like below:
async function main() {
const response = await queryAsPromise(
`SELECT id, full_name, email,mobile from frms WHERE status = ? AND email IS NOT NULL`,
[1]
);
// Rest of your code...
}
Why don't you just use a promisified helper function to execute your queries and return the result?
// DB setup
const dbConfig = {
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME,
port: process.env.DATABASE_PORT,
}
// Connection handler
const handleConnection = () => {
return new Promise((resolve, reject) => {
const client = mysql.createConnection(dbConfig); // Recreate the connection, since the old one cannot be reused.
client.connect(function onConnect(err) { // The server is either down
if (err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleConnection, 10000); // We introduce a delay before attempting to reconnect,
return;
} // to avoid a hot loop, and to allow our node script to
console.log('Database connected.');
resolve(client);
});
// process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
client.on('error', function onError(err) {
console.log('db error', err);
if (err.code == 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleConnection(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
reject(err); // server variable configures this)
}
});
})
}
// Query handler
export.mySql = (query, values = null) => {
return new Promise(async (resolve, reject) => {
try {
const client = await handleConnection();
let db = client;
db.query(query, values, (err, result, fields) => {
if (!err) {
resolve(result);
client.end();
console.log('Query executed');
return;
}
client.end();
throw err;
});
} catch (error) {
reject(err);
}
});
}
So whenever you call the mySql function; it connects to DB, executes the query, and returns the result.
Usage:
const { mySql } = require('./db.js');
const result = await mySql(`SELECT id, full_name, email,mobile from frms WHERE status = ? AND email IS NOT NULL`, ['1']);
console.log(result);

discord.js find claim time in giveaways using roles

I recently added this to my bot where it checks for the roles and sends a message in the channel where it sends the claim time of the user.
module.exports = {
name: 'giveaway',
description: ':tada: the new winner is',
execute(message, args){
let winner = message.mentions.members.first();
const ouser = message.mentions.users.first();
var time = 10000;
var support = 0;
var donate = 0;
var boost = 0;
const allowedRole = winner.roles.cache.find(r => r.name === '・Supporter') || winner.roles.cache.find(r => r.name === 'Nitro・Donator') || winner.roles.cache.find(r => r.name === '・Booster')
if (!allowedRole) {
message.channel.send(`Congratulations **${ouser.username}**! You have ${time / 1000} seconds to DM the host!`)
.then(message => {
setTimeout(function() {
message.channel.send(`${time / 1000} seconds up!`)
}, time)
})
return;
}
switch (allowedRole.name) {
case '・Supporter':
support = 3000;
break;
case 'Nitro・Donator':
donate = 5000;
break;
case '・Booster':
boost = 5000;
}
var newTime = (time + support + donate + boost));
const user = message.mentions.users.first();
message.channel.send(`Congratulations **${user.username}**! You have ${newTime / 1000} seconds to DM the host!`)
.then(message => {
setTimeout(function() {
message.channel.send(`${newTime / 1000} seconds up!`)
}, newTime)
})
}
}
I'm not sure how to add the time for the total claim time since + isn't working. I tried using time - (- support) - (-donate) - (-boost)) but it only showed 13 seconds (supporter role). Any fix to this?
The problem is in this line
const allowedRole = winner.roles.cache.find(r => r.name === '・Supporter') || winner.roles.cache.find(r => r.name === 'Nitro・Donator') || winner.roles.cache.find(r => r.name === '・Booster')
allowedRole can be set to only one role but a user can have multiple roles.
You can do something like this
module.exports = {
name: "giveaway",
description: ":tada: the new winner is",
execute(message, args) {
const winner = message.mentions.members.first();
let DefaultTime = 10;
let support = 0;
let donate = 0;
let boost = 0;
//get all the roles of the winner in an array
const userRoles = winner.roles.cache.map((r) => r.name);
//Check if the user have the allowed roles and set time according to that (There might be a better way to do this instead of using if statements for each of them seperately)
if (userRoles.includes("・Supporter")) {
support = 3;
}
if (userRoles.includes("Nitro・Donator")) {
donate = 5;
}
if (userRoles.includes("・Booster")) {
boost = 5;
}
const TotalTime = DefaultTime + support + donate + boost;
message.channel
.send(
`Congratulations **${winner.user.username}**! You have ${TotalTime} seconds to DM the host!`
)
.then((message) => {
setTimeout(function () {
message.channel.send(`${TotalTime} seconds up!`);
}, TotalTime * 1000);
});
},
};

nodejs async how to set callback

I have the following piece of code which is working fine.
var config = require('./config');
var cheerio = require('cheerio');
var myhttp = require('./myHttp');
var stringHelper = require('./stringHelper');
var Base64 = require('./base64.js').Base64;
var Encrypt = require('./Encrypt.js');
var myEncode = require('./Encode.js');
var rules = require('./rules');
var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
var mysql = require('mysql');
delete require.cache[require.resolve('./requestLogin1.js')]
var myvar = require('./requestLogin1.js');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'abc',
database : 'abcd'
}
);
connection.connect(function(err) {
if (err) {
console.log('error connecting: ' + err.stack);
return;
}
});
var timerOB;
var timerMW;
var timerP;
var timerTL;
var news = {
'mw': [],
'ob': [],
'all': {},
};
var status = false;
function round(rnum, rlength) {
return newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function roundup(rnum, rlength) {
return newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function rounddown(rnum, rlength) {
return newnumber = Math.floor(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function function1(_html) {
console.log('function1 run')
var $ = cheerio.load(_html);
var v_lgnid = $('#userId').attr('value');
var v_psswrd = config.password;
var v_data = v_lgnid + "|" + v_psswrd;
var _key = $('#accntid').attr('value');
if (_key) {
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, _key , "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidPassword.jsp?' + $('#name').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
function2();
} else {
console.log('Login Fail');
}
});
} else {
login();
console.log('Encrypt password error');
}
}
function function2() {
myhttp.get(
'https://example.com/QuestionsAuth.jsp',
function (_htmlShowImage) {
var $ = cheerio.load(_htmlShowImage);
var sLoginID = $('#sLoginID').attr('value');
var Answer1 = config.answer1;
var Answer2 = config.answer2;
var Index1 = $('#st1').attr('value');
var Index2 = $('#st2').attr('value');
var v_data = sLoginID + "|" + Answer1 + "|" + Answer2 + "|" + Index1 + "|" + Index2;
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, $('#key_questauth').attr('value'), "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidAnswers.jsp?' + $('#name_questauth').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
//rootCallback();
myhttp.get(
'https://example.com/DefaultLogin.jsp',
function (_html) {
console.log('Login sucess')
stringHelper.SaveFileCookies('abcd.txt', myhttp.loadCookie(), 'save cookie login sucess');
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
if (timerP) {
clearTimeout(timerP);
}
timerP = setTimeout(function4, config.function4);
});
} else {
console.log('Login Fail - timer');
}
});
});
}
var login = function () {
if (timerMW) {
clearTimeout(timerMW);
}
if (timerOB) {
clearTimeout(timerOB);
}
if (timerP) {
clearTimeout(timerP);
}
if (timerTL) {
clearTimeout(timerTL);
}
myhttp.init();
myhttp.post(
'https://example.com/ShowImage.jsp',
{ "requiredLogin": myEncode.Convert(config.uname) },
function (_htmlpost) {
if (_htmlpost) {
function1(_htmlpost);
} else {
if (timerTL) {
clearTimeout(timerTL);
}
timerTL = setTimeout(login, config.DelayNestError);
}
});
}
exports.login = login;
function function3() {
return {
TS: '',
MWP: 0,
LTP: 0,
NQ: 0,
OBBP: '',
OBSP: '',
CurrTime: 0,
rules: {}
};
}
function function4() {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
});
}
function function5() {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
});
}
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
console.log('MW - Step 9 - logged out');
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
}
Now i want to use async to ensure that function6 is run only after function4 & function5 is run.
I have tried to learn about async from various forums and have changed the code as follows:
var async = require('async'); //line added
// change made
async.parallel([
function function4(callback) {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
console.log('Posn - Step 3A - Found position:' + symbol);
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
callback(); //line added
});
},
function function5(callback) {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0 || statusOrder.toLowerCase().indexOf('trigger pending') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
console.log('OB - Step 5 - pushed to html page');
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
callback(); //line added
});
}
],
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
//new check rules
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
});
Since my original functions do not have any callback, and since async needs callback, i have tried to code a callback in function4 & function5 - but I guess i have not coded it correctly.
I am getting an error in the line where callback is present that states "TypeError: undefined is not a function".
How do i correct this?
Related Question No. 2 : the current code has a timer function whereby function4, function5 and function6 runs with a preset timer. If async works, how do i define a timer whereby the combined set of function4,5 & 6 works based on a preset timer?
Sorry about the long code -- i am new to nodejs and was handed over this code as such and am trying to get this change made.
Thanks for your guidance.
You can instead make function4 and function5 to return promise and then execute function6 only after both function4's and function5's promise gets resolved.

Resources