Expected '(' when testing js in console - javascript

The following is my javascript and receiving an
Expected '(' error
in console.
//GLOBALS
var _debug = false;
//
function tryParseInt(accountNumber) {
if (_debug) {
console.log("Entering tryParseInt: " + new Date().toTimeString());
}
try{
//var retValue = defaultValue;
if(accountNumber !== null) {
if(accountNumber.length > 0) {
if (!isNaN(accountNumber)) {
//retValue = parseInt(accountNumber);
return true;
}
}
}
return false;
}
catch{
console.log("Failed at tryParseInt:");
console.log(err);
console.log("---------------------------------");
}
}
I can't for the life of me figure why. Any extra eye will help.

this should be
catch (error) {
}

Related

AngularJS - refactor code to Service/Factory

I am need to refactor some code and convert it into a factory/service calls. This was the original code being cslled for an autocomplete dropdown.
$scope.querySearchManagerName = function (skill) {
console.log(skill);
//var entry = skill.replace(/ /g, "_").toLowerCase()
var query = {
"managerName" : skill
}
if(skill.length < 2){
return [query]
}
else{
return $http.post('/tdp/managerTypeahead/', query)
.then(function(result) {
return result.data;
})
.catch(function(reason) {
$scope.genericError();
}
)
}
}
The factory code I have converted to is :
var querySearchManagerName = function(skill) {
var query = {
"managerName" : skill
}
return $http.post('/tdp/managerTypeahead/', query)
.then(function(result) {
return result.data;
})
.catch(function(reason) {
$scope.genericError();
}
)
}
And calling of the factory is :
$scope.querySearchManagerName = function (skill) {
console.log(skill);
//var entry = skill.replace(/ /g, "_").toLowerCase()
var query = {
"managerName" : skill
}
if(skill.length < 2){
return [query]
}
else{
return $scope.demandFactory.querySearchManagerName(skill);
}
}
However I am getting an error :
TypeError: $scope.demandFactory.querySearchManagerName is not a function.
Any clue why i am getting it?

Why is this async function failing to return any data?

So, a quick overview, this function is part of a larger app that ingests JSON data and prepares it to be rendered by Handlebars, which is then used for generating a PDF. This particular function has been giving me grief, as from my understanding of how async/await works, the data should be returned by the return returnArray at the bottom of the function. This however does not happen, and instead the empty array is returned. Could anyone offer insight as to why this is? (N.B. I've checked the data is present in iarr when it gets pushed, it's as though the return statement gets fired before the for loop has started.)
async function getPackageItem(item) {
try {
let returnArray = []
if (fs.existsSync(__dirname + "/../json/" + item.sku + ".json")) {
var file = fs.readFileSync(__dirname + "/../json/" + item.sku + ".json")
} else {
var file = fs.readFileSync(__dirname + "/../json/box.json")
}
const tb = JSON.parse(file);
for (var a = 0; a < item.quantity; a++) {
let iarr = [];
if (tb) {
tb.forEach(function(entry) {
ShopifyAuth.get('/admin/products/' + entry.product_id + '.json', (err, productData) => {
if (!err) {
ShopifyAuth.get('/admin/products/' + entry.product_id + '/metafields.json', (err, metafieldData) => {
if (!err) {
var itemObject = {};
var metaCounter = 0;
metafieldData.metafields.forEach(function(metadata) {
switch(metadata.key) {
case "notes": {
itemObject.wm_notes = metadata.value;
metaCounter++
break;
}
case "title": {
itemObject.title = metadata.value;
metaCounter++
break;
}
case "vintage": {
itemObject.year = metadata.value;
metaCounter++;
break;
}
case "shelfid": {
itemObject.shelf_id = metadata.value;
metaCounter++;
break;
}
case "bottleprice": {
itemObject.bottle_price = metadata.value;
metaCounter++;
break;
}
default: {
metaCounter++;
break;
}
}
if(metaCounter === metafieldData.metafields.length) {
itemObject.vendor = productData.product.vendor;
if (itemObject.title == undefined) {
itemObject.title = productData.product.title
}
if (itemObject.wm_notes == undefined) {
itemObject.wm_notes = " "
}
if (itemObject.year == undefined) {
itemObject.year = "Unspecified"
}
if (itemObject.shelf_id == undefined) {
itemObject.shelf_id = "N/A"
}
if (productData.product.images[1] == undefined) {
if (productData.product.images[0]) {
itemObject.logo = productData.product.images[0].src;
} else {
itemObject.logo = '';
};
} else {
itemObject.logo = productData.product.images[1].src;
}
itemObject.quantity = item.quantity;
iarr.push(itemObject)
if(iarr.length == tb.length) {
returnArray.push(iarr);
}
}
});
} else {
throw Error('Error retrieving product metadata');
}
})
} else {
throw Error('Error retrieving product data');
}
})
})
} else {
throw Error('Error loading JSON for specified box');
}
}
return returnArray;
} catch (e) {
console.log(e)
}
}
Edit: That's what I get for writing code at 3am, not sure how I missed that. Thanks for your feedback.
You marked your function async but you're not using await anywhere inside of it so you're not getting any of the benefits of using async. It doesn't make your function magically synchronous, you still have to manage asynchronicity carefully.
If ShopifyAuth.get supports returning a promise then await on the result instead of passing callbacks and your code will work, otherwise construct a Promise, do the async stuff in the promise, and return the promise from the function.
async function getPackageItem(item) {
let result = new Promise((resolve, reject) => {
// all your ShopifyAuth stuff here
if (err) {
reject(err);
}
resolve(returnArray);
});
return result;
}

Why does this function causes a "Maximum call stack size exceeded"

I have been trying to figure this out for days now, The app.js returns a "Maximum call stack size exceeded" after I logged "Debug: 3". I am new to Javascript, so I'm not sure if I'm creating functions that call themselves in a loop or something. Here is the function that is run and causes an error.
function sendNewUserPackage(node) {
console.log("Debug: 00");///////////////////////////////
for (var i in SOCKET_LIST) {
console.log("Debug: 01");///////////////////////////////
var s = SOCKET_LIST[i];
if (node === 1) {
for (var n in Node1.NODE_PLAYERS) {
console.log("Debug: 02");///////////////////////////////
var pl = Node1.NODE_PLAYERS[n];
if (s.id === pl.id) {
console.log("Debug: 03");///////////////////////////////Code never reaches Debug: 5 at the end of the function
s.emit('newUserPackage', Node1.NODE_PLAYERS);
}
}
}
else if (node === 2) {
console.log("Debug: 04");///////////////////////////////
for (var n in Node2.NODE_PLAYERS) {
var pl = Node2.NODE_PLAYERS[n];
if (s.id === pl.id) {
s.emit('newUserPackage', Node2.NODE_PLAYERS);
}
}
}
else if (node === 3) {
for (var n in Node3.NODE_PLAYERS) {
var pl = Node3.NODE_PLAYERS[n];
if (s.id === pl.id) {
s.emit('newUserPackage', Node3.NODE_PLAYERS);
}
}
}
}
console.log("Debug: 05");///////////////////////////////
}
function sendClientMessage(socket, message) {
socket.emit('message', message);
}
Here is how sendNewUserPackage() is called:
socket.on('loginAttempt', function(data) {
//Check credentials with database...
try {
console.log("Debug: 1");///////////////////////////////
Database.checkAccount(data.username, data.password, function(error, result) {
console.log("Debug: 2");///////////////////////////////
if (result === undefined) {
socket.emit('loginMessage', {status:false});
return;
}
if (result.length > 0) {
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
var player = new Player(socket.id, result[0].Username, result[0].Rank, result[0].Points);
player.socket = socket;
PLAYER_LIST[socket.id] = player;
console.log("Debug: 3");///////////////////////////////
var nodeNumber = selectGameNode();
console.log("Debug: 4");///////////////////////////////
if (nodeNumber === 1) {
Node1.addPlayer(player);
console.log("Debug: 98");///////////////////////////////
} else if (nodeNumber === 2) {
Node2.addPlayer(player);
console.log("Debug: 99");///////////////////////////////
} else if (nodeNumber === 3) {
Node3.addPlayer(player);
console.log("Debug: 100");///////////////////////////////
} else {
console.log("Debug: 5");///////////////////////////////
player.node = 0;
socket.emit('loginMessage', {status:true});
sendClientMessage(player.socket, 'Whoops! Looks like all games are full! Try again later!')
return;
}
console.log("Debug: 6");///////////////////////////////
socket.emit('loginMessage', {status:true});
sendNewUserPackage(player.node);
return;
}
console.log("Debug: 7");///////////////////////////////
socket.emit('loginMessage', {status:false});
});
} catch(err) {
console.log(err.message);
}
});
What confuses me about it is that each "Debug: num" that is called only shows up once in the console. So I think that means neither function is called more than once. Could something else be causing it?
Help is greatly appreciated!

Handling presence in Strophe js

I have a simple chat application build with strophe js. I am showing the only users who are online. But the problem is when the user goes online, after some seconds the users goes offline automatically.
Here is my code:
function onConnect(status)
{
// Functions runs while users trys to login to the XMPP server
var iq = null;
switch (status)
{
case Strophe.Status.CONNECTING:
log('Connecting.');
break;
case Strophe.Status.CONNFAIL:
log('Failed to connect.');
$('#connect').get(0).value = 'connect';
break;
case Strophe.Status.DISCONNECTING:
log('Disconnecting.');
break;
case Strophe.Status.DISCONNECTED:
log('Disconnected.');
$('#connect').get(0).value = 'connect';
break;
case Strophe.Status.CONNECTED:
log('Connected.');
connection.addHandler(onMessage, null, 'message', null, null, null);
connection.addHandler(onPresence, null, 'presence', null, null, null);
iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'});
connection.sendIQ(iq, onRoster);
break;
default:
break;
}
}
function onPresence(pres)
{
var fromJid = $(pres).attr("from"),
fromBareJid = Strophe.getBareJidFromJid(fromJid),
myBareJid = Strophe.getBareJidFromJid(connection.jid),
type = $(pres).attr("type"),
show = $(pres).children("show").text(),
statusMsg = $(pres).children("status").text(),
contactDropDown = $('#to-jid'),
line;
$.each(roster, function (index, rosterEntry) {
if (rosterEntry.jid === fromBareJid) {
if (type === "unavailable") {
rosterEntry.presence = "offline";
rosterEntry.message = null;
} else {
if (show) {
rosterEntry.presence = show;
} else {
rosterEntry.presence = 'online';
}
if (statusMsg) {
rosterEntry.message = statusMsg;
} else {
rosterEntry.message = null;
}
}
}
});
showRoster();
if (fromBareJid !== myBareJid) {
if (type !== 'unavailable') {
if (!_.contains(onlineContacts, fromBareJid)) {
onlineContacts.push(fromBareJid);
}
line = fromBareJid + " is ";
if (show) {
line += show;
} else {
line += "online";
}
if (statusMsg) {
line += ", \"" + statusMsg + "\"";
}
showMessage(line);
} else {
onlineContacts = _.reject(onlineContacts, function (jid) {
return (jid === fromBareJid);
});
showMessage(fromBareJid + " is offline");
}
contactDropDown.empty();
contactDropDown.append($("<option />").text("Choose a contact..."));
$.each(onlineContacts, function (index, contact) {
contactDropDown.append($("<option />").val(contact).text(contact));
});
}
return true;
}
function onRoster(iq) {
$(iq).find('item').each(function () {
var jid = $(this).attr('jid'),
name = $(this).attr('name'),
show = "",
rosterEntry = {
jid: jid,
name: name,
presence: 'offline',
message: null
};
roster.push(rosterEntry);
});
// showRoster();
connection.send($pres().tree());
}
function showRoster() {
rosterbox.val("");
$.each(roster, function (index, rosterEntry) {
var line = "";
line += rosterEntry.jid;
if (rosterEntry.name) {
line += " (" + rosterEntry.name + ")";
}
line += ": " + rosterEntry.presence;
if (rosterEntry.message !== null) {
line += ", \"" + rosterEntry.message + "\"";
}
rosterbox.val(rosterbox.val() + line + "\n");
});
}
With this code, the user goes offline automatically. Cant find where's the exact problem. Please help

How to make loop wait for callback in node.js?

I have scenario. Where i Want to execute loop after data has been updated in mongodb. Means Like that :
var i = 0;
while (i< 5) {
attendanceDataModel.update(query, condition).exec(function(error, data) {
if (error) {
console.log("Error # 168 line in app.js File : \n" + err + "\n");
i++;
} else {
if (data.length <= 0) {
console.log("No Records Matched.");
i++;
} else {
console.log(currEmpId + " : successfully Logged Out ! :-)" + data + "\n");
updateRecordNumber(currRecordNumber);
i++; //wrong because it increases the value before updating in DB.
}
}
});
}
var updateRecordNumber = function(currRecordNumber) {
var condition = { deviceLogId: parseInt(currRecordNumber) };
lastDeviceLogIdModel.update({}, condition).exec(function(error, data) {
if (error) {
console.log("Error # 213 line in app.js File : \n" + err + "\n");
} else {
if (data.length <= 0) {
console.log("No Records Matched." + "\n");
} else {
console.log(currRecordNumber + " : DeviceLogId successfully Updated ! :-)");
// I want to increase value of i here after updation in database
}
}
});
}
Now, I want to increase variable i value after function updateRecordNumber has successfully updated
Simplest way is change function like var updateRecordNumber = function(currRecordNumber, callback) and then change invocation: updateRecordNumber(currRecordNumber, function(){ i++ });
But I think it's a much better solution to use some control flow approach, e.g. Promises or Async.js
P.S. of course you have to change function's body:
var updateRecordNumber = function(currRecordNumber, callback) {
// all your async stuff
callback();
}
Code can be changed to:
var i = 0;
function startUpdation() {
return attendanceDataModel.update(query, condition).exec(function(error, data) {
if (error) {
console.log("Error # 168 line in app.js File : \n" + err + "\n");
i++;
if (i<5) {
return startUpdation();
}
return;
} else {
if (data.length <= 0) {
console.log("No Records Matched.");
i++;
if (i<5) {
return startUpdation();
}
return;
} else {
console.log(currEmpId + " : successfully Logged Out ! :-)" + data + "\n");
return updateRecordNumber(currRecordNumber).then(function (err, data){
i++;
if (i<5) {
return startUpdation();
}
return;
});
}
}
});
}
function updateRecordNumber (currRecordNumber) {
var condition = { deviceLogId: parseInt(currRecordNumber) };
return lastDeviceLogIdModel.update({}, condition).exec(function(error, data) {
if (error) {
console.log("Error # 213 line in app.js File : \n" + err + "\n");
} else {
if (data.length <= 0) {
console.log("No Records Matched." + "\n");
} else {
console.log(currRecordNumber + " : DeviceLogId successfully Updated ! :-)");
}
}
});
}
startUpdation();
Please try this solution.
It would be better if you promisify function updateRecordNumber and write the increment call in the then().
Your while loop is synchronous and does not factor in that the response to your database operation will return sometimes later.
You need to requery after an unsuscessful operation through recursively rescheduling the operation (with an drop out after 5 tries):
function execute(count, callback) {
if (count == 5) {
return callback(new Error('meh...'))
}
loadSomethingAsync(function(error, result) {
if (error || !result) {
return execute(count++, callback)
}
callback(null, result)
})
}
execute(0, function(error, result) {
if (error) {
return console.log('after 5 tries still no result or error...')
}
console.log('yay, async op has finished!')
})
How about refactoring the loop to itself be part of the callback? Something like this:
var i = 0,
fna = function (error, data) {
if (error) {
console.log("Error # 168 line in app.js File : \n" + err + "\n");
fnc(); //i++;
} else {
if (data.length <= 0) {
console.log("No Records Matched.");
fnc(); //i++;
} else {
console.log(currEmpId + " : successfully Logged Out ! :-)" + data + "\n");
updateRecordNumber(currRecordNumber);
//i++; //wrong because it increases the value before updating in DB.
}
}
},
updateRecordNumber = function (currRecordNumber) {
var condition = {
deviceLogId : parseInt(currRecordNumber, 10)
};
lastDeviceLogIdModel.update({}, condition).exec(fnb);
},
fnb = function (error, data) {
if (error) {
console.log("Error # 213 line in app.js File : \n" + err + "\n");
} else {
if (data.length <= 0) {
console.log("No Records Matched." + "\n");
} else {
console.log(currRecordNumber + " : DeviceLogId successfully Updated ! :-)");
// I want to increase value of i here after updation in database
fnc();
}
}
},
fnc = function () {
i++;
if (i < 5) {
attendanceDataModel.update(query, condition).exec(fna);
}
};
attendanceDataModel.update(query, condition).exec(fna);
You can use synchronize module in node js .You can see my blog enter link description here

Categories

Resources