javascript league api combinedTick callback - javascript

async run(message, args) {
LolApi.init('censored', 'na');
LolApi.setRateLimit(10, 500);
var input = '';
args = args.toLowerCase();
LolApi.Summoner.getByName(args, function (err, summoner) {
if (!err) {
Name = summoner[args].name;
Name = Name.toLowerCase();
Id = summoner[Name].id;
Level = summoner[Name].summonerLevel;
input += "Name: " + summoner[Name].name + '\n' +
"Level: " + Level + "\n";
console.log(input);
//message.reply(input);
process.nextTick(LolApi.getLeagueData);
}
else {
message.reply('Error fam.');
}
});
setTimeout(function(){console.log('Waiting...')},2000);
LolApi.getLeagueData(Id,'NA', function (err, summoner) {
if (!err) {
Tier = summoner[Id][0].tier;
Division = summoner[Id][0].entries[0].division;
input += "Tier: " + Tier + '\n' +
"Division: " + Division;
message.reply(input);
} else {
console.log(Name);
console.log(err);
message.reply('Error Fam' + Id + "test");
}
});
}
When i run this code up get an error 404 running the second part. It gives me an saying combinedTickCallback but im not sure what this means because i am a noob. I use node.js if that helps with anything

Related

Excel JavaScript API - problem with passing variables between multiple ".then()"

I'm trying to pass variables between a chain of ".then()" calls like so:
Excel.run(function (context) {
var currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
var table = currentWorksheet.tables.getItem("NewTable");
table.rows.load('count')
return context.sync()
.then(function () {
var rowCount = table.rows.count;
console.log("There are " + rowCount + " rows in the table.");
var firstColumn = table.columns.getItem(1);
firstColumn.load("values");
return context.sync();
})
.then(function () {
var firstColumnValues = firstColumn.values;
var summary = {};
for (var i = 0; i < firstColumnValues.length; i++) {
var value = firstColumnValues[i][0];
if (summary[value]) {
summary[value]++;
} else {
summary[value] = 1;
}
}
console.log(summary);
})
.catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
})
.catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
But I get an error:
Error: ReferenceError: firstColumn is not defined
How can I pass variables in a chain of ".then()" calls?
i think you have your then in the the wrong place
the second then looks like it should be attached to the second sync not the first
Excel.run(function(context) {
var currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
var table = currentWorksheet.tables.getItem("NewTable");
table.rows.load("count");
return context.sync().then(function() {
var rowCount = table.rows.count;
console.log("There are " + rowCount + " rows in the table.");
var firstColumn = table.columns.getItem(1);
firstColumn.load("values");
return context
.sync()
.then(function() {
var firstColumnValues = firstColumn.values;
var summary = {};
for (var i = 0; i < firstColumnValues.length; i++) {
var value = firstColumnValues[i][0];
if (summary[value]) {
summary[value]++;
} else {
summary[value] = 1;
}
}
console.log(summary);
})
.catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
});
}).catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
however i think you would be greatly helped by switching to the async/await syntax, also notice that the use of var for variable declaration is frowned on these days and is a hold over from the early days of javascript before it had the concept of scoping so can lead to some very odd side effects, you should use const and let (const for a variable that will be set once and read many or let for a variable that can be set and read many times)
Excel.run(async function(context) {
const currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
const table = currentWorksheet.tables.getItem("NewTable");
table.rows.load("count");
await context.sync().catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
const rowCount = table.rows.count;
console.log("There are " + rowCount + " rows in the table.");
const firstColumn = table.columns.getItem(1);
firstColumn.load("values");
await context.sync().catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
const firstColumnValues = firstColumn.values;
const summary = {};
for (let i = 0; i < firstColumnValues.length; i++) {
const value = firstColumnValues[i][0];
if (summary[value]) {
summary[value]++;
} else {
summary[value] = 1;
}
}
console.log(summary);
});

Callback skipped a part

I have some trouble with my js callback, I can't understand why my callback of my function don't want execute all the code, just to give you an idea :
class LogsPortail {
static SetLogs(pool, req, res, callback) {
console.log('start log ');
var bCallBack = false;
var now = new Date();
var endpoint = req.originalUrl
endpoint = endpoint.split("?")[0]
endpoint = endpoint.replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
var queryParam = "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ";
console.log('query 1 log ');
pool.query(query, function(err, results) {
if (err) {
console.log("Error : " + query);
bCallBack = true;
callback();
} else {
console.log('query log 2');
//On a bien inséré le logs portail, maintenant on ajout tous les paramètres
for (var key in req.query) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.query[key] + "')"
}
for (var key in req.body) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.body[key] + "')"
}
pool.query(queryParam, function(err, resultsParam) {
if (err) {
console.log("Error : " + queryParam);
console.log(err);
bCallBack = true;
callback();
} else {
bCallBack = true;
callback();
}
});
}
});
while (bCallBack === false) {}
console.log('call back end ');
//callback();
}
}
To explain you, my first query will be executed perfectly, and after that, the callback will not go through the condition but will go at the end where (for the test) I put an infinity while where my code will never exit.
This is what my log shows - we never see the logs "query log 2"
Thanks for your help

Variable not retaining value

I am attempting to set a variable to results obtained from a query, but the variable is not retaining the value.
var queryString = "SELECT price FROM menu_items WHERE id = " +
req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
if (err){
next(err);
return;
}
itemPrice = rows[0].price;
console.log("item price is2: " + itemPrice);
});
console.log("item price is: " + itemPrice);
I expect it to print "item price is2: 10.99" and then "item price is 10.99" but it prints item price is undefined and then item price is2: 10.99
var queryString = "SELECT price FROM menu_items WHERE id = " +
req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
if (err){
next(err);
return;
}
itemPrice = rows[0].price;
console.log("item price is2: " + itemPrice);
console.log("item price is: " + itemPrice);
});
var queryString = "SELECT price FROM menu_items WHERE id = " +
req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
if (err){
next(err);
return;
}
itemPrice = rows[0].price;
console.log("item price is2: " + itemPrice);
console.log("item price is: " + itemPrice);
});
Any network calls, run asynchronously, so once the db call is made, the next lines start executing.
Using Async Await
const {promisify} = require('util');
(async ()=> {
var queryString = "SELECT price FROM menu_items WHERE id = " +
req.query.items + ";";
const query = promisify( mysql.pool.query).bind(mysql.pool);
const result = await query(queryString)
if (!result) {
next(result);
return;
}
console.log(result)
itemPrice = result[0].price;
console.log("item price is2: " + itemPrice);
console.log("item price is: " + itemPrice);
})()
you can do it using following method
export const getPriceValue = async () => {
var queryString = "SELECT price FROM menu_items WHERE id = " +
req.query.items + ";";
mysql.pool.query(queryString, function(err, rows, fields){
if (err){
return 0;
}
if(row) {
return(rows[0].price);
}
});
}
let priceValue = await getPriceValue();
console.log('price::', priceValue);

Node sqlite3 when to close db

I cannot figure out when to close a db in node-sqlite3, or really how to use the package in general. It seems if I run this, I get "no such table:rooms". Eventually after running it enough times, I might manage to make the table.
var sqlite3 = require('sqlite3').verbose();
class RoomManager{
constructor(options){
this.db = this._createDb();
this.table = "rooms";
this._createTable();
this.addRoom({
name : 'test3'
}).getRooms()
this.deleteRoom({
name : 'test3'
}).getRooms();
return this;
}
_createDb() {
return new sqlite3.Database('chat');
}
_createTable(){
this.db.run("CREATE TABLE IF NOT EXISTS " + this.table + " (name TEXT, size INT)");
return this;
}
addRoom(options){
this.db.run("INSERT INTO " + this.table + " (name, size) VALUES ($name, $size)", {
$name : options.name,
$size : options.size || 1000
});
return this;
}
getRooms(){
this.db.all("SELECT rowid, name, size FROM " + this.table, function(err, rows) {
rows.forEach(function (row) {
console.log(row.rowid + ": " + row.name + " - " + row.size);
});
});
return this;
}
getRoom(options){
if(options.name){
this.db.get("SELECT * FROM " + this.table + " WHERE name = $name", {
$name : options.name
}, function(err, row){
return row;
});
}
}
deleteRoom(options){
this.db.run("DELETE FROM " + this.table + " WHERE name = $name", {
$name : options.name
});
return this;
}
}
module.exports = RoomManager;
Your problem that Node is asynchronous. So, you must wait end of command by callback function. e.g.
this.db.run(query, params, function(err) {
if (err)
return console.log(err);
// do next query here
})
Sqlite module can control flow by db.serialize. Imho it's useless in common cases. Better use async module or promises for it.

Unit testing a function and simulating an event emitter response

I am currently writing some tests against the code shown below in node.js using mocha. I want to simulate the response from the event emitter 'check_user'. I have sinon.js but I can't get my mind in the right place to work out the best way to simulate the response.
Anyone able to offer some advice on how to go about this?
TgCustomCommand.contact = new Command("contact", "Will send you a users contact card to add to your contact list. Usage is .contact nick", function (input, callback) {
var payload = input;
//Switch our contact to payload.to as this is what our checkuser function looks at
//Check the command over
if (payload.command_args === false) {
payload.response = 'msg ' + payload.to + ' ' + this.description;
return callback(null, payload);
} else {
payload.return = payload.to;
payload.to = payload.command_args; //Set up ready for nick check
//Check the nick exists
emitter.emit('check_user', payload, function (err, result) {
if (err) return callback(err, null);
payload = input; //Reset our payload so we have correct payload.to
//Check how many users we returned
if (result.length === 0) { //Not in our contact list
payload.response = 'msg ' + payload.return + ' I do not have that person in my contact list!';
return callback(null, payload);
} else if (result.length === 1) {
payload.to = result[0].Nick;
payload.response = "send_contact " + payload.return + ' ' + result[0].Phone + ' ' + result[0].Nick + " _";
return callback(null, payload);
}
else {
//loop through our object and create a list of those returned
payload.response = "msg " + payload.return + " I know multiple people with a similar nick: ";
for (var i = 0; i < result.length; i++) {
log.debug(result[i].Nick);
payload.response = payload.response + result[i].Nick + " ";
}
return callback(null, payload);
}
});
}
;
});

Categories