Javascript execution order when using if statements - javascript

I am a novice here, I apologize for any ignorance. I am trying to create a family feud game for personal use using node.js and express as the server and socket.io for communication between clients. I ran into an issue with this particular function where if there are less than 5 players it will include all but the last one in the socket message. For example if there are 3 players it seem to be running the player4 else statement (for when blank) before completing the player3 variable assignment. I have tried researching it and found promises and async/await but I don't understand it enough to make it work for my situation or if it would even apply. This is a lot of nested if statements. I feel like a loop would be better but not sure how to do it properly. Any help and suggestions are much appreciated.
if (data.teamNum == 'team1') {
team1.teamNum = 'team1';
fs.access('./public/images/players/' + data.player1, function(error) {
if (error) {
console.log(data.player1 + " icons do not exist.")
team1.player1pic = "default"
} else {
console.log(data.player1 + " icons exist.")
fs.readdir('./public/images/players/' + data.player1, (error, files) => {
team1.player1pic = files; // return the number of files
console.log(data.player1 + " has " + team1.player1pic + " pics.");
});
}
if (data.player2 != 'blank') {
fs.access("./public/images/players/" + data.player2, function(error) {
if (error) {
console.log(data.player2 + " icons do not exist.")
team1.player2pic = "default"
} else {
console.log(data.player2 + " icons exist.")
fs.readdir('./public/images/players/' + data.player2, (error, files) => {
team1.player2pic = files; // return the number of files
console.log(data.player2 + " has " + team1.player2pic + " pics.");
});
}
if (data.player3 != 'blank') {
fs.access("./public/images/players/" + data.player3, function(error) {
if (error) {
console.log(data.player3 + " icons do not exist.")
team1.player3pic = "default"
} else {
console.log(data.player3 + " icons exist.")
fs.readdir('./public/images/players/' + data.player3, (error, files) => {
team1.player3pic = files; // return the number of files
console.log(data.player3 + " has " + team1.player3pic + " pics.");
});
}
if (data.player4 != 'blank') {
fs.access("./public/images/players/" + data.player4, function(error) {
if (error) {
console.log(data.player4 + " icons do not exist.")
team1.player4pic = "default"
} else {
console.log(data.player4 + " icons exist.")
fs.readdir('./public/images/players/' + data.player4, (error, files) => {
team1.player4pic = files; // return the number of files
console.log(data.player4 + " has " + team1.player4pic + " pics.");
});
}
if (data.player5 != 'blank') {
fs.access("./public/images/players/" + data.player5, function(error) {
if (error) {
console.log(data.player5 + " icons do not exist.")
team1.player5pic = "default"
} else {
console.log(data.player5 + " icons exist.")
fs.readdir('./public/images/players/' + data.player5, (error, files) => {
team1.player5pic = files; // return the number of files
console.log(data.player5 + " has " + team1.player5pic + " pics.");
console.log('sending pics');
feud.in(data.room).emit('teampics', team1);
});
}
});
} else {
console.log('sending pics');
feud.in(data.room).emit('teampics', team1);
}
});
} else {
console.log('sending pics');
feud.in(data.room).emit('teampics', team1);
}
});
} else {
console.log('sending pics');
feud.in(data.room).emit('teampics', team1);
}
});
} else {
console.log('sending pics');
feud.in(data.room).emit('teampics', team1);
}
});
}

I hope the code is self explanatory. I haven't tested the getPlayerPic function. I used callback('default') for the test.
If you have to write same code more then twice always make it a function which you run multiple times. The code will be much easier to read as well as easier to find the problem.
// function to get the player picture
function getPlayerPic(player, callback) {
//return callback('default' + player);
fs.access('./public/images/players/' + player, function(error) {
if (error) return callback('default');
fs.readdir('./public/images/players/' + data.player1, (error, files) => {
callback(files);
});
});
};
// test data
var data = {
teamNum: 'team1',
player1: 'p1',
player2: 'p2',
player3: 'p3',
player4: 'blank',
player5: 'blank',
}
var team1 = {};
if (data.teamNum == 'team1') {
team1.teamNum = 'team1';
var players = Object.keys(data).filter(p => p.startsWith('player')).reverse();
// players = [ 'player1', 'player2', 'player3', 'player4', 'player5' ];
function next(callback) {
var p = players.pop(); // pop an item from players
console.log('p', p);
if (p && data[p] && data[p] !== 'blank') // if it exists and is not blank
getPlayerPic(data[p], function(pic){
team1[p + 'pic'] = pic;
next(callback);
});
else // we are done here
callback();
};
next(function(){
console.log('sending pics', team1);
/*
sending pics { teamNum: 'team1',
player1pic: 'defaultp1',
player2pic: 'defaultp2',
player3pic: 'defaultp3' }
*/
});
}

Here's a more functional approach to the same problem.
(If you become enamored of functional programming, check out JS Allongé.)
Caveat rogantis: This code is completely untested, and I'd bet money it will require debugging. I didn't look into how fs.access and fs.addredir work so it may also need to be refactored to make the callbacks legal.
const { teamNum, room, player1, player2, player3, player4, player5 } = data;
const playersList = [player1, player2, player3, player4, player5];
let done;
// We're only dealing with team1 for now
const team1 = {};
let team = team1;
team.teamNum = teamNum;
// Assigns icons for each player (stops if a blank player is found)
for(let player of playersList){
assignIcons(player);
if(isLastPlayer(player)){
break;
}
}
// Primary functions
function assignIcons(player){
fs.access(getPath(player), accessCallback(error, player));
}
function accessCallback(error, player){
if (error) {
// Logs "player has no icons" and assigns default
logPlayerHasIcons(player, false);
assignIconCount(player, "default");
}
else {
// Logs "player has icons" and gets the count
logPlayerHasIcons(player, true);
fs.readdir(getPath(player), readdirCallback(error, fileCount, player);
}
}
function readdirCallback(error, fileCount, player){
// Assigns the icon count for this player
if(error){ console.log(error); }
assignIconCount(player, fileCount);
logIconCount(getPlayerNum(player), fileCount);
// Emits pics if done
if(isLastPlayer(player)){
emitPics();
}
}
function emitPics(){
console.log('sending pics');
feud.in(room).emit('teampics', team);
}
function assignIconCount(player, val){
const
playerNum = getPlayerNum(player),
playerPicPropName = `player${playerNum}pic`;
team[playerPicPropName] = val;
}
// Supporting functions
function isLastPlayer(player){
const playerNum = getPlayerNum();
return (
(playerNum == 5) ||
(playersList[playerNum] == "blank") // playerNum = index of next player
);
}
function getPlayerNum(player){
return playersList.indexOf(player) + 1;
}
function getPath(player){
return "./public/images/players/" + player;
}
function logPlayerHasIcons(player, doesHaveIcons){
console.log(`${player} ${(doesHaveIcons ? "has" : "has no")} icons`);
}
function logIconCount(playerNum, count){
console.log(`player${playerNum} has ${count} pics`);
}

Related

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;
}

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

Need help comparing the value inside array, with forEach loop

So basically I have some promise, forEach, just a lot of issues with this single problem I need to solve. So the variables I work with has below structure:
persons = [object, object, object]
where each object has { user:number , username: string, latitude:number, longitude:number}
from there I try to figure out if my user/username is inside of one of these objects, if not found id like it to be created, if found found id like it to update their location. Sounds simple, I think the problem has blown out of proportion but nothing works. The code I have now does not work, its either I can never figure out when the user is not there, or I can not figure out how to get to stop creating me every time it find a user who is not me.
var getswamp = function(item, index) {
return new Promise(function(resolve, reject){
var result = false;
if (item.user === user && item.username === username) {
if ((item.latitude !== latitudenew) || (item.longitude !== longitudenew)) {
var id = item.id;
swampdragon.update('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username,
id: id
}, function (context, data) {
console.log("data updated", data);
result = true;
resolve(result);
}, function (context, data) {
console.log("You may not be updated");
});
} else {
console.log("No location change");
result = true;
}
}else{
if ( item.index === person.index){
console.log(person);
resolve(result)
}
}
});
};
person.forEach(function (item, index) {
var swamping = getswamp(item, index);
swamping.then(function (result) {
console.log(result);
if (result === true) {
console.log("We have you");
} else if (result === false && (index === person.length - 1)) {
console.log('Index: ' + index + ' Length of list is ' + person.length);
swampdragon.create('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username
}, function (context, data) {
console.log("data created", data);
}, function (context, data) {
console.log("You may not be created")
});
}
})
});
Any help/ideas would just be great.
The Promise is used when some asynchronous event happened.
Since I can not create such event, I made a static code as below:
var persons = new Array();
persons.indexOf = function(person) {
var index = -1;
this.forEach(function(obj, i) {
if (person.username == obj.username) {
index = i;
}
});
return index;
}
persons.addOrUpdate = function(person) {
var index = this.indexOf(person);
if (index == -1) {
person.user = this.length + 1;
this.push(person);
}
else { // update case
var obj = this[index];
obj.latitude = person.latitude;
obj.longitude = person.longitude;
}
}
persons.print = function() {
var str = "";
this.forEach(function(obj) {
str += obj.user + ". " + obj.username + " at location (" +
obj.latitude + ":" + obj.longitude + ")\n";
});
return str;
}
persons.addOrUpdate({username:'Adam', latitude:-0.0045, longitude:14.2015});
persons.addOrUpdate({username:'Eve', latitude:-0.0045, longitude:14.2015});
persons.addOrUpdate({username:'Abel', latitude:-0.0045, longitude:14.2015});
// Updating Able location
var person = {username:'Abel', latitude:10.1145, longitude:14.1234};
persons.addOrUpdate(person);
alert(persons.print());

chrome Event is not dispatched

I'm having a little problem. I thought I had understood Event Handling, but now I don't think so anymore.
I've created a Chrome Event():
this.onReadLine = new chrome.Event();
this event is dispatched in a function:
this.onReadLine.dispatch(line);
before the dispatch instruction I've tried to log 'line', the argument of the dispatch instruction. No problem, 'line' exists.
Going straight down with the code you will find this part:
connection.onReadLine.addListener(function(line) {
logJSON(line);
});
this is what must be fired every time the onReadLine event is dispatched.
The problem is that the Event onReadLine is only dispatched when I push or release the button '#dimmer1_Chrome_Input' defined at the end of my code.
Where I'm wrong?
My full code here. The parts related to problem are highlighted with ////\///\/\///\\ lines.
// Serial used from Arduino board
const Arduino_COM = 'COM3'; // PC
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.boundOnDataReceiving = this.onDataReceiving.bind(this);
this.boundOnDataReceivingError = this.onDataReceivingError.bind(this);
this.onConnect = new chrome.Event();
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
this.onReadLine = new chrome.Event();
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
this.onError = new chrome.Event();
};
SerialConnection.prototype.connect = function(Serial_COM_Port) {
chrome.serial.connect(Serial_COM_Port, this.onConnectComplete.bind(this));
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnDataReceiving);
chrome.serial.onReceiveError.addListener(this.boundOnDataReceivingError);
this.onConnect.dispatch();
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
chrome.serial.send(this.connectionId, String_to_ArrayBuffer(msg), function() {});
};
SerialConnection.prototype.onDataReceiving = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ArrayBuffer_to_String(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('\n')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
console.log(line);
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
this.onReadLine.dispatch(line);
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onDataReceivingError = function(errorInfo) {
if (errorInfo.connectionId === this.connectionId) {
this.onError.dispatch(errorInfo.error);
}
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
chrome.serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + Arduino_COM);
});
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
connection.onReadLine.addListener(function(line) {
logJSON(line);
});
///////////////////////////\\\\\\\\\\\\\\\/////////////\\\\\\\\\\////////\\\\\\\\\\\\////////\\\\\\\\\\//////PROBLEM
connection.connect(Arduino_COM);
function logJSON(result) {
var response = jQuery.parseJSON( result );
dimmer1_state = response.dimmer1_state;
dimmer1_value = response.dimmer1_value;
SerialIn = response.SerialIn;
dimmer1_Chrome_Input = response.dimmer1_Chrome_Input;
temperature1_value = response.temperature1_value;
s=Math.round(dimmer1_value * 80 / 255 + 20);
hsl='hsl(115,'+s+'%,60%)';
if (dimmer1_state == 0)
{
$('#statusCircle').css('fill','hsl(115,20%,60%)');
}
else
{
$('#statusCircle').css('fill', hsl);
};
// Print led Status to HTML buffer area
messaggio = "dimmer1 state: " + dimmer1_state
+ "<br />dimmer1 value: " + dimmer1_value
+ "<br />SerialIn: " + SerialIn
+ "<br />dimmer1_Chrome_Input: " + dimmer1_Chrome_Input
+ "<br />temperature1_value: " + temperature1_value + " °C";
log(messaggio);
};
function log(msg) {
$('#buffer').html(msg);
};
$(function(){
$('#dimmer1_Chrome_Input') .button()
.mousedown(function() {
connection.send("101");
})
.mouseup(function() {
connection.send("100");
});
});
The code is correct, the error was in another part of program

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