Right now this section of code is passing along undefined to if(customerWaiting >0). It's an issue with async that I can't seem to figure out.
Based off the other threads I looked at, it's very basic and a newbie question, I just can't make it work.
I was seeing if you could find it for me
Edit 1:
the goal of the code is to see if there are customers in the firebase "customerWaiting" database, if there is then display the modal, if there is not then say there are no customers waiting
structure for database is
customerWaiting
-Automatically generated ID
-customer information
Here is the code
var customerWaiting;
var employeeWaiting;
var ref = firebase.database().ref();
$("#connectNextUser").click(function() {
{
ref.child("customerWaiting").on("value", function(snapshot) {
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
});
ref.child("employeeWaiting").on("value", function(snapshot) {
var employeeWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " employees waiting");
});
}
if (customerWaiting > 0) {
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});
If I understand you correctly you want to do this:
var ref = firebase.database().ref();
$("#connectNextUser").click(function() {
// query how many customers are waiting
ref.child("customerWaiting").on("value", function(snapshot) {
// as soon as you have the result then get the numChildren
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
// show the modal if customerWaiting > 0
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});
});
If you want to use await/async then ref.child("customerWaiting").on("value", resolve) has to support Promises, or you need to convert it to one:
var ref = firebase.database().ref();
$("#connectNextUser").click(async function() {
var snapshot = await new Promise((resolve, reject) => {
ref.child("customerWaiting").on("value", resolve)
// you should also handle the error/reject case here.
})
var customerWaiting = snapshot.numChildren();
console.log("There are " + snapshot.numChildren() + " customers waiting");
if (customerWaiting > 0) {
$("#myModal").modal();
console.log("connect");
} else {
console.log("There are " + customerWaiting + " employees waiting");
console.log("no connect");
}
});
Related
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);
});
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
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.
I have the following data array in my Firebase app. I want to delete Account3 using AngularFire's $remove method but I can't get it to work
[MY-FIREBASE-URL]
users
simplelogin:1
accounts
0
title: "Account1"
1
title: "Account2"
2
title: "Account3"
3
title: "Account4"
4
title: "Account5"
This is the code I'm using
var fbURL = [MY-FIREBASE-URL];
var ref = new Firebase(fbURL);
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
var accountPath = fbURL + "/users/" + authData.uid + "/accounts/" + account.title;
//alert(accountPath);
var accountRef = new Firebase(accountPath);
accountRef.remove();
} else {
console.log("User is logged out");
}
In the console.log I see the correct user in the authData but nothing happens. What am I doing wrong?
Try this. I altered the accountRef variable and your $remove() function:
var fbURL = [MY-FIREBASE-URL];
var ref = new Firebase(fbURL);
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
var accountPath = fbURL + "/users/" + authData.uid + "/accounts/" + account.title;
//alert(accountPath);
var accountRef = $firebaseObject(accountPath);
accountRef.$remove().then(function(accountPath) {
console.log("data has been deleted locally and in Firebase");
}, function(error) {
console.log("Error:", error);
});
} else {
console.log("User is logged out");
}
Thank you #MattDionis for you help. I finally found the answer to my question so here it is for any other newbies like me struggling with a similar issue. In the sample code above the Firebase URL was referencing "account.title" which in fact I needed "account.id", based on the data structure above, to actually remove the entry from my Firebase data.
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);
}
});
}
;
});