Java Script array get undefined - javascript

when I print the whole array it's print.but if I try to print element by element it's print as undefined.this is my function. I print the arrays at end of the function.client functions are used to connect ajax API.i tried to get integer id that matching to a specific string from database via ajax functions and push them into the two arrays.
function fetch() {
var arrayForClass = [];//this is a array get undefined at the end
var arrayForMessage = [];//this is a array get undefined at the end
exceptionPattern ="";
receivedData.length = 0;
var queryInfo;
var queryForSearchCount = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
}
};
client.searchCount(queryForSearchCount, function (d) {
if (d["status"] === "success" && d["message"] > 0) {
var totalRecordCount = d["message"];
queryInfo = {
tableName: "LOGANALYZER",
searchParams: {
query: "_eventTimeStamp: [" + from + " TO " + to + "]",
start: 0, //starting index of the matching record set
count: totalRecordCount //page size for pagination
}
};
client.search(queryInfo, function (d) {
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
for (var i = 0; i < obj.length; i++) {
if(obj[i].values._level === "ERROR" || obj[i].values._level === "WARN"){
receivedData.push([{
date: new Date(parseInt(obj[i].values._eventTimeStamp)).toUTCString(),
level: obj[i].values._level,
class: obj[i].values._class,
content: obj[i].values._content,
trace: (obj[i].values._trace ? obj[i].values._trace : ""),
timestamp: parseInt(obj[i].values._eventTimeStamp)
}]);
}else{
continue;
}
}
console.log(receivedData);
for (forLoopI = 0; forLoopI < receivedData.length; forLoopI++){
var className = receivedData[forLoopI][0].class;
var strclassname = className.toString();
var messageContent = receivedData[forLoopI][0].content;
queryInfo = {
tableName: "EXCEPTION_CLASS_FOR_ERROR_PATTERNS",
searchParams: {
query: "class_name: "+ strclassname + "",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
if (d["status"] === "success") {
var num = obj[0].values.id;
var strnum = num.toString();
arrayForClass.push(strnum);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
queryInfo = {
tableName: "ERROR_MESSAGE_CONTENTS",
searchParams: {
query: "message: \""+ messageContent + "\"",
start: 0, //starting index of the matching record set
count: 1 //page size for pagination
}
};
client.search(queryInfo,function(d){
var obj = JSON.parse(d["message"]);
console.log(obj);
if (d["status"] === "success") {
var num2 = obj[0].values.id;
var strnum2 = num2.toString();
arrayForMessage.push(strnum2);
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","error while creating the error pattern" +
" please try again"));
}
},function(error){
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
}else{
$(canvasDiv).html(gadgetUtil.getCustemText("No content to display","there are no error patterns which include this error" +
" please try another one"));
}
}, function (error) {
console.log(error);
error.message = "Internal server error while data indexing.";
onError(error);
});
console.log("------------------");
for (var j = 0; j < 8; j++) {
console.log(arrayForClass[j]);//prints undefine
}
console.log("------------------");
console.log(arrayForClass[0]); //prints undefine
console.log(arrayForClass);//prints corectly
console.log(arrayForMessage);//printd corectly
}

Your API call is asynchronous, which mean it's continue working to the next line even your call is not finished.
You get undefined because your console.log reference to the not exists yet variable. arrayForClass is empty at that moment, so arrayForClass[0] is not exists.
Next line you get correct result because you console.log to an existing variable, even it's empty at the moment, but your debugger tool is trying to be smart by update it for you in the console when your data came in.
if you really want to see the actual value at that point, you need to somehow make it immutable, for example :
console.log(JSON.parse(JSON.stringify(arrayForClass)));
This is only explain why you get data in the console like that.If you need to use those variable, It's has to be done inside those callback function regarding each calls.

Related

Parsing large CSV file in LWC

I have implemented the following code to parse a csv file, convert to a JSON array and send the JSON result to apex controller, which invokes the batch class to process the DML operation for opportunityLineItem object. The code is working fine up to a maximum of 4000 rows (files have 22 columns with values). When there are 5000 records, the process throws an error and stops (it does not call the apex server). Why does it stop if there are 4000 records? Is there any limit for parsing the csv records in LWC?
Code:
if (!this.csvFile) {
console.log("file not found");
return;
}
this.showprogressbar = true;
let reader = new FileReader();
let ctx = this; // to control 'this' property in an event handler
reader.readAsText(this.csvFile, "Shift_JIS");
reader.onload = function (evt) {
console.log('reader:'+evt.target.result);
let payload = ctx.CSV2JSON(evt.target.result, ctx.CSVToArray);
let json = null;
let error = null;
console.log("payload:" + payload);
setJSON({
payload: payload,
crud: crud,
csvFile:ctx.csvFile
})
.then((result) => {
json = result;
var err = json.includes("Error");
console.log('err====='+err);
if(err)
{
console.log('json==###=='+json);
ctx.error = json;
console.log("error:"+ctx.error);
///s/ alert('error');
ctx.showloader=false;
ctx.hasError=true;
}
else{
ctx.jobinfo(json);
console.log("apex call setJSON() ===> success: " + json);
//ctx.error = undefined;
}
})
.catch((error) => {
error =ctx.error;
console.log("error:" + error.errorCode + ', message ' + error.message);
///s/ alert('error');
ctx.showloader=false;
ctx.hasError=true;
if (error && error.message) {
json = "{'no':1,'status':'Error', 'msg':'" + error.message + "'}";
} else {
json = "{'no':1,'status':'Error','msg':'Unknown error'}";
}
});
};
reader.onerror = function (evt) {
/*ctx.mycolumns = [
{ label: "no", fieldName: "no", type: "number", initialWidth: 50 },
{
label: "status",
fieldName: "status",
type: "text",
initialWidth: 100
},
{ label: "message", fieldName: "msg", type: "text" }
];
ctx.mydata = [{ no: "1", status: "Error", msg: "error reading file" }];
*/
//$A.util.toggleClass(spinner, "slds-hide"); // hide spinner
};
// ctx.showloader=false;
console.log("mydata:===" + ctx.mydata);
alert('onerror');
}
CSV2JSON(csv, csv2array) {
let array = csv2array(csv);
//console.log("csv:::"+csv);
//console.log("csv2array:"+csv2array);
let objArray = [];
//console.log("objArray:"+objArray);
var headervar = oppheader;//'Name,BillingCity,Type,Industry';
console.log('headervar:::'+headervar);
let headerArray = headervar.split(',');
for (let i = 1; i < array.length; i++) {
objArray[i - 1] = {};
/*for (let k = 0; k < array[0].length && k < array[i].length; k++) {
let key = array[0][k];
if(key === 'DW予定日')
elseif(key === 'DW予定日')
elseif(key === 'DW予定日')
console.log("key:"+key);
this.hearder=key;
objArray[i - 1][key] = array[i][k];
}*/
for (let k = 0; k < headerArray.length; k++) {
let key = headerArray[k];
console.log("key====:"+key);
this.hearder=key;
objArray[i - 1][key] = array[i][k];
}
}
objArray.pop();
//console.log("objArray:==="+objArray.length);
this.rowCount = objArray.length;
//console.log("rowCount+++++++" + this.rowCount);
let json = JSON.stringify(objArray);
//console.log("json:==="+json.length);
let str = json.replace("/},/g", "},\r\n");
//console.log("str:======="+str);
return str;
}
CSVToArray(strData, strDelimiter) {
console.log('CSVToArray');
// Check to see if the delimiter is defined. If not,
// then default to comma.
//console.log('strData:'+strData);
//console.log("strDelimiter::" + strDelimiter);
strDelimiter = strDelimiter || ",";
//console.log("strDelimiter:" + strDelimiter);
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
// Delimiters.
"(\\" +
strDelimiter +
"|\\r?\\n|\\r|^)" +
// Quoted fields.
'(?:"([^"]*(?:""[^"]*)*)"|' +
// Standard fields.
'([^"\\' +
strDelimiter +
"\\r\\n]*))",
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
// console.log("objPattern:" + objPattern);
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
// console.log("arrData:" + arrData);
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while ((arrMatches = objPattern.exec(strData))) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && strMatchedDelimiter != strDelimiter) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(new RegExp('""', "g"), '"');
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return arrData;
}

Javascript global variables and references to them and their parts

I'm writing little snippets to learn more about using Javascript with API's, and have stumbled onto another problem I can't figure out on my own. I have a global variable (object?) "coins", read in from the API, and its' data field "symbol". I can use "symbol" to reference the data held there, in part of my code, without any errors. Later in the code, I use it again, and I get an error about it being undefined, despite the fact that the values returned from using it, are both defined, and, what I expected. While we are at it, maybe someone can tell me why I assign values to global variables (declared outside of all of the functions), but the variables when called, are "undefined". To see it in action, visit www.mattox.space/XCR and open up dev tools.
/*
FLOW:
get ALL coins, store NAME and SYMBOL into an object.
loop over the names object comparing to $SYMBOL text from form, return the NAME when found.
hit the API again, with the $NAME added to the URL.
create a table row.
insert data from second API hit, into table row
SOMEWHERE in there, do the USD conversion from BTC.
*/
//var name = getName();
var bitcoinValue = 0;
var coins = new Array;
var form = ""; // Value pulled from the form
var symbol = ""; // "id" on the table
var id = ""; // value pulled from the table at coins[i].id matched to coins[i].symbol
var formSym = "";
var formUSD = 0;
var formBTC = 0;
var form24h = 0;
function run() {
getFormData();
allTheCoins("https://api.coinmarketcap.com/v1/ticker/");
testGlobal();
}
function testGlobal() {
console.log("These are hopefully the values of the global variables");
console.log(formSym + " testGlobal");
console.log(formUSD + " testGlobal");
console.log(formBTC + " testGlobal");
console.log(form24h + " testGlobal");
}
function getFormData(){ //This function works GREAT!
form = document.getElementById("symbol").value //THIS WORKS
form = form.toUpperCase(); //THIS WORKS
}
function allTheCoins(URL) {
var tickerRequest = new XMLHttpRequest();
tickerRequest.open('GET', URL);
tickerRequest.send();
tickerRequest.onload = function() {
if (tickerRequest.status >= 200 && tickerRequest.status < 400) {
var input = JSON.parse(tickerRequest.responseText);
for(var i in input)
coins.push(input[i]);
testFunction(coins);
}
else {
console.log("We connected to the server, but it returned an error.");
}
console.log(formSym + " allTheCoins!"); // NOPE NOPE NOPE
console.log(formUSD) + " allTheCoins!"; // NOPE NOPE NOPE
console.log(formBTC + " allTheCoins!"); // NOPE NOPE NOPE
console.log(form24h + " allTheCoins!"); // NOPE NOPE NOPE
}
}
function testFunction(coins) {
for (var i = 0; i < coins.length; i++) {
if (coins[i].symbol == form) { // But right here, I get an error.
formSym = coins[i].name;
formUSD = coins[i].price_usd;
formBTC = coins[i].price_btc;
form24h = coins[i].percent_change_24h;
console.log(formSym + " testFunction");
console.log(formUSD + " testFunction");
console.log(formBTC + " testFunction");
console.log(form24h + " testFunction");
//DO EVERYTHING RIGHT HERE! On second thought, no, this needs fixed.
}
else if (i > coins.length) {
formSym = "Error";
formUSD = 0;
formBTC = 0;
form24h = 0;
}
}
}
/*
if (24h >= 0) {
colorRED
}
else {
colorGreen
}
*/
here is a possible way of doing it that you can get inspired by. its based on a httpRequest promise that set the headers and method.
let allTheCoins = obj => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(obj.method || obj.method, obj.url);
if (obj.headers) {
Object.keys(obj.headers).forEach(key => {
xhr.setRequestHeader(key, obj.headers[key]);
});
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send(obj.body);
});
};
allTheCoins({
url: "https://api.coinmarketcap.com/v1/ticker/",
method: "GET",
headers: {"Accept-Encoding": "gzip"}
})
.then(data => {
ParseCoins(data);
})
.catch(error => {
console.log("We connected to the server, but it returned an error.");
});
function ParseCoins(data) {
const coins = JSON.parse(data);
const form = getFormVal();/*retrieve form val*/
const id = getTableId(); /*retrieve table id*/
const bitcoinValue = getBitcoinVal();/*retrieve bitcoin Value*/
const final_result = [];
for (let i = 0, len = coins[0].length; i < len; i++) {
const coin = coins[0][i];
for (let ii in coin) {
if (coin.hasOwnProperty(ii)) {
if (coin[ii].symbol == form) {
let element = {
formSym: coin[ii].name,
formUSD: coin[ii].price_usd,
formBTC: coin[ii].price_btc,
form24h: coin[ii].percent_change_24h
};
final_result.push(element);
}
}
}
}
coontinueElseWhere(final_result);
}

Access Database Via Javascript

I am creating a HTA application since my environment has restrictions. In any case I am trying to connect to an Access Database through a prototype. This prototype is suppose to get the information from the database but it always returns as "undefined". I am unable to determine as to why this is occurring as i am using the ActiveX controls that open that provider.
The Calling function
Please note that the access drivers are installed, the location is correct and the table does exists with content.
function GetX()
{
var db = new AccessDatabase("I:\\Office\\Access\\Sample.accdb");
db.Connect();
if (db.Status != 0) { return; }
// Remove all
$("#x").empty();
// The Query
var results = db.Select("SELECT x FROM Tracker");
// Get the results length
var arrayLength = results.length;
// Iterate through the results
for (var row = 0; row < arrayLength; row++)
{
$("#x").append("<option id='" + results[row][0] + ">" + results[row][0] + "</option>");
}
db.Disconnect();
}
The prototype object:
function AccessDatabase(databaseSource)
{
try
{
this.Connection = new ActiveXObject("ADODB.Connection");
this.Source = databaseSource;
this.Status = 0;
}
catch (err)
{
createNotification("Danger", "Unable to create ActiveX Control For Microsoft ");
this.Status = err.Number;
}
}
AccessDatabase.prototype.Connect = function()
{
try
{
var provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + this.Source;
this.Connection.Open(provider);
}
catch (err)
{
createNotification("Danger", "Database Failed To Connect. Was the Source correct?<br>Details: " + err.message);
this.Status = err.Number;
}
}
AccessDatabase.prototype.Disconnect = function()
{
this.Connection.Close();
}
AccessDatabase.prototype.Select = function (selectQuery)
{
try
{
// Open the recordset
var recordSet = new ActiveXObject("ADODB.Recordset");
recordSet.Open(selectQuery, this.Connection);
// Check for null results
if (recordSet.RecordCount == null || recordSet.RecordCount == -1)
{
createNotification("Error", "No record was found for the query provided <br> Query: <small>"
+ selectQuery + "</small>");
recordSet.Close();
this.Status = -1;
return null;
}
alert("Record Count:" + recordSet.RecordCount);
// Convert To Array
var returnValue = recordSet.GetRows();
recordSet.Close();
// Return the array
return returnValue;
}
catch (err)
{
createNotification("Warning", "Query Could Not Execute Due to an error. <br>Details: " + err.message);
this.Status = err.Number;
}
}

Getting JSON from a Function in javascript

So this will be a lot of code, but what matter is on line 22-25, and line 87-91. The rest of the code works. I have a nested function and want to return the JSON string. Using console.log I can tell it is running properly but will not return the JSON string. Look for the part that says //---------this part-------. There are two parts that I am asking about.
exports.post = function(request, response) {
var mssql = request.service.mssql;
//var data = '{"userID":"ryan3030#vt.edu1"}';
var inputJSON = request.body.JSONtext;
var json = JSON.parse(inputJSON);
var userID = json.userID;
mssql.query("EXEC getMeetingInfo ?", [userID],
{
success: function(results3) {
var meetingsToday = results3.length;
var meetingID = results3[0].meetingID;
var meetingName = results3[0].meetingName;
var meetingDescription = results3[0].meetingDescription;
var meetingLength = results3[0].meetingLength;
var meetingNotes = results3[0].meetingNotes;
var hostUserID = results3[0].hostUserID;
//--------------------------------------THIS PART------------------------------
var JSONfinal = allInfoFunction(mssql, meetingID, userID, meetingName, meetingDescription, meetingLength, meetingNotes, hostUserID, meetingsToday);
console.log(JSONfinal);//DOES NOT WORk
response.send(statusCodes.OK, JSONfinal);//DOES NOT WORK
//---------------------------------BETWEEN THESE----------------------------------
},
error: function(err) {
console.log("error is: " + err);
response.send(statusCodes.OK, { message : err });
}
});
};
function allInfoFunction(mssql, meetingID, userID, meetingName, meetingDescription, meetingLength, meetingNotes, hostUserID, meetingsToday){
mssql.query("EXEC getLocation ?", [meetingID],
{ success: function(results2) {
var meetingLocation = results2[0].meetingLocation;
var JSONlocation = {"meetingLocation": meetingLocation};
mssql.query("EXEC getDateTime ?", [meetingID],
{ success: function(results1) {
var length = results1.length;
var dateTime = [];
dateTime[0] = results1[0].meetingDateTime;
for (var x= 1; x < length; x++) {
dateTime[x] = results1[x].meetingDateTime;
}
//console.log(dateTime);
mssql.query("EXEC getDateTimeVote",
{ success: function(results) {
//console.log(results);
var JSONoutput2 = {};
var JSONtemp = [];
var length2 = results.length;
for(var j = 0; j < length; j++){
var vote = false;
var counter = 0;
for(var z = 0; z < length2; z++){
var a = new Date(results[z].meetingDateTime);
var b = new Date(results1[j].meetingDateTime);
if(a.getTime() === b.getTime()){
counter = counter + 1;
}
if((a.getTime() === b.getTime()) && (results[z].userID == userID)){
vote = true;
}
}
var meetingTimeInput = {"time": b, "numVotes": counter, "vote": vote}
JSONtemp.push(meetingTimeInput);
JSONoutput2.meetingTime = JSONtemp;
}
var JSONfinal = {};
var mainInfoArray = [];
var JSONmainInfo = {meetingID: meetingID, meetingName: meetingName, meetingDescription: meetingDescription, meetingLength: meetingLength, meetingNotes: meetingNotes, hostUserID: hostUserID, meetingLocation: meetingLocation };
JSONmainInfo.meetingTime = JSONtemp;
JSONfinal.numMeetingsToday = meetingsToday;
mainInfoArray.push(JSONmainInfo);
JSONfinal.meetingList = mainInfoArray;
//response.send(statusCodes.OK, JSONfinal);
//---------------------------------------AND THIS PART-------------------------------
console.log(JSON.stringify(JSONfinal));//This outputs the correct thing
var lastOne = JSON.stringify(JSONfinal);
return lastOne; //ths dosent work
//-------------------------------------BETWEEN THESE-----------------------------------
},
error: function(err) {
console.log("error is: " + err);
//response.send(statusCodes.OK, { message : err });
}
});
},
error: function(err) {
console.log("error is: " + err);
//response.send(statusCodes.OK, { message : err });
}
});
},
error: function(err) {
console.log("error is: " + err);
//response.send(statusCodes.OK, { message : err });
}
});
}
I've done a little refactoring to your code to take a more modular approach. It becomes quite tricky to debug something like what you have above. Here it is:
exports.post = function(request, response) {
var mssql = request.service.mssql;
var inputJSON = request.body.JSONtext;
var json = JSON.parse(inputJSON);
var userID = json.userID;
var JSONFinal = {};
getMeetingInfo(userID);
function getMeetingInfo(userID){
mssql.query("EXEC getMeetingInfo ?", [userID], {
success: function(results){
JSONFinal.meetingsToday = results.length;
JSONFinal.meetingID = results[0].meetingID;
JSONFinal.meetingName = results[0].meetingName;
JSONFinal.meetingDescription = results[0].meetingDescription;
JSONFinal.meetingLength = results[0].meetingLength;
JSONFinal.meetingNotes = results[0].meetingNotes;
JSONFinal.hostUserID = results[0].hostUserID;
// Call next function
getLocation(JSONFinal);
},
error: function(err) {
console.log("error is: " + err);
response.send(statusCodes.OK, { message : err });
}
});
}
function getLocation(){
mssql.query("EXEC getLocation ?", [JSONFinal.meetingID], {
success: function(results) {
JSONFinal.meetingLocation = results[0].meetingLocation;
// Call next function
getDateTime(JSONFinal);
},
error: function(err) {
console.log("error is: " + err);
}
});
}
function getDateTime(){
mssql.query("EXEC getDateTime ?", [JSONFinal.meetingID], {
success: function(results) {
var length = results.length;
var dateTime = [];
for (var x= 0; x < length; x++) {
dateTime[x] = results[x].meetingDateTime;
}
// Call next function
getDateTimeVote(dateTime);
},
error: function(err){
console.log("error is: " + err);
}
});
}
function getDateTimeVote(dateTime){
mssql.query("EXEC getDateTimeVote", {
success: function(results) {
var JSONtemp = [];
var length2 = results.length;
for(var j = 0; j < dateTime.length; j++){
var vote = false;
var counter = 0;
for(var z = 0; z < length2; z++){
var a = new Date(results[z].meetingDateTime);
var b = new Date(results1[j].meetingDateTime);
if(a.getTime() === b.getTime()){
counter = counter + 1;
}
if((a.getTime() === b.getTime()) && (results[z].userID == userID)){
vote = true;
}
}
var meetingTimeInput = {"time": b, "numVotes": counter, "vote": vote}
JSONtemp.push(meetingTimeInput);
}
var JSONmainInfo = {
meetingID: JSONFinal.meetingID,
meetingName: JSONFinal.meetingName,
meetingDescription: JSONFinal.meetingDescription,
meetingLength: JSONFinal.meetingLength,
meetingNotes: JSONFinal.meetingNotes,
hostUserID: JSONFinal.hostUserID,
meetingLocation: JSONFinal.meetingLocation
meetingTime: JSONtemp
};
var JSONfinal = {
numMeetingsToday: JSONFinal.meetingsToday,
meetingsList: [JSONmainInfo]
};
// Call next function
sendResponse(JSON.stringify(JSONfinal));
},
error: function(err) {
console.log("error is: " + err);
}
});
}
function sendResponse(data){
response.send(statusCodes.OK, data);
}
};
It looks a lot different but the functionality is pretty much the same. The key point if you look at the code is that each subsequent function is executed only after the success of the previous function. This effectively chains the methods together so that they are always executed in order and is the key point of difference.
One thing to note here is the similarity between your
allInfoFunction(...
and my
getMeetingInfo(userID)
Both of these will return undefined more or less immediately, after the MSSQL query is sent to the server. This is because the request is fired asynchronously, and the javascript continues to run through the code. After it's fired of the asynchronous request, it has nothing left to do in that function, so it returns. There is no return value specified so it returns nothing (or undefined if you will).
So all in all, the code in the question code will return undefined and then attempt to send a response before anything has actually happened. This code fixes that problem by firing the sendResponse after all the queries have been executed.
I refactored this code in a text editor and haven't run it, or checked it for errors, so follow the basic outline all you like but it may not be a good idea to copy and paste it without checking it's not broken

For loop going out of range? [duplicate]

This question already has answers here:
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 4 months ago.
I am using a library in Javascript to pull in data from a chat server. The library is irrelevant but is quickblox. The data comes back into my app and can be seen, but when I try an loop on an object they return, it goes out of range, can't get 'last_message' of undefined. Loop should run for res.items[i].length which at the mo is two, but it is trying to carry on running, it seems.
var onDialogs = function(err, res){
console.log("------------------------------------List Of Dialogs------------------------------------",res);
var count = 0;
var sent;
var i = 0;
console.log("res.items.length",res.items.length)
for (i;i<=res.items.length;i++){
console.log("this one: ", res.items[i]);
if (res.items[i].last_message===null||res.items[i].last_message===undefined||res.items[i].last_message===""){
alert("SOMETHING WENT WRONG");
}
else{
console.log("RES.ITEMS: ", res.items);
console.log("RES ITEMS LEN", res.items.length);
console.log("***********************I IS SET TO: ",i," *******************************************");
console.log("RAWR",res.items);
console.log(res.items[i].last_message_date_sent,res.items[i].last_message);
console.log(res.items[i]);
if (res.items[i].last_message === undefined || res.items[i].last_message===null || res.items[i].last_message===""){
console.log("FAIL");
}
else{
var dialogID = res.items[i]._id;
var sent = res.items[i].created_at;
console.log(res.items[i].created_at);
var year = sent.substring(0,4);
var month = sent.substring(5,7);
var day = sent.substring(8,10);
var userIDInChat;
var j =0;
userArray=[];
var userArray = res.items[i].occupants_ids;
console.log("USER ARRAY: ",userArray);
for (j; j<userArray.length; j++){
console.log(userArray[j]);
var testID = window.localStorage.getItem("userID");
console.log("USERARRAY[j]", userArray[j]);
if (userArray[j] != testID){
console.log("INSIDE THE IF STATEMENT");
userIDInChat = userArray[j];
window.localStorage.setItem("userIDInChat", userIDInChat);
console.log("//*******BLOCK ID SET TO********\\", userIDInChat, testID, res);
$.get("http://www.domain.co.uk/API/getUserByID.php", { userID: userIDInChat}, function (data) {
console.log("API CALL:",data);
chatOpponent = data;
console.log(chatOpponent);
console.log("------------------------------------------------------------------------------------------");
renderBlock(res,j,i,chatOpponent,userIDInChat,userArray,testID,day,month,year,dialogID);
});
}
}
}
}
}
//End block
};
function renderBlock(res,j,i,chatOpponent,userIDInChat,userArray,testID,day,month,year,dialogID){
console.log("(res,j,i,chatOpponent,userIDInChat,userArray,testID)");
console.log("RENDERBLOCK PARAMS: ",res,j,i,chatOpponent,userIDInChat,userArray,testID);
//insert function here
console.log("RES: ",res);
var senderID = userIDInChat;
//compare date - vs. moment - today, yesterday or date
sent = day + "/" + month + "/" + year;
console.log(sent);
var onMessages = function(err,result){
window.localStorage.setItem("RESULTTEST",result);
console.log("ONMESSAGESRESULTHERE",err,result);
//console.log("---------onMessages---------",result.items[i].date_sent);s
};
var msgList = QB.chat.message.list({chat_dialog_id: dialogID}, onMessages);
var messages;
console.log(messages);
if (res.items[i].last_message.length>=140) {
var last_message = res.items[i].last_message.substring(0,140)+".....";
}
else{
var last_message = res.items[i].last_message;
}
var readFlag = res.items[i].read;
console.log("SENDERID:", senderID, "username: ", chatOpponent, "last_message", last_message, "sentFlag");
if (readFlag === 1){
var read = "fa-envelope-o";
}
else {
var read = "fa-envelope";
}
var html = "<div class='messageBlock' id='"+senderID+"'><div style='width:10%;min-height:64px;float:left;'><i class='fa '"+read+"'></i><p>"+sent+"</p></div><div style='width:90%;min-height:64px;float:right;'><p class='user'><b><i>"+chatOpponent+"</b></i></p><p>"+last_message+"</p></div></div>";
Object being looped on:
Object {total_entries: 2, skip: 0, limit: 50, items: Array[2]}items: Array[2]0: Object_id: "54e4bd3929108282d4072a37"created_at: "2015-02-18T16:26:33Z"last_message: "test"last_message_date_sent: 1425640757last_message_user_id: 2351789name: nulloccupants_ids: Array[2]photo: nulltype: 3unread_messages_count: 0user_id: 2351781xmpp_room_jid: null__proto__: Object1: Object_id: "54ec990f29108282d40b19e2"created_at: "2015-02-24T15:30:23Z"last_message: "herro!"last_message_date_sent: 1424858692last_message_user_id: 2394026name: nulloccupants_ids: Array[2]photo: nulltype: 3unread_messages_count: 0user_id: 2351789xmpp_room_jid: null__proto__: Objectlength: 2__proto__: Array[0]limit: 50skip: 0total_entries: 2__proto__: Object
for (i;i<=res.items.length;i++){
should be
for (i;i<res.items.length;i++){
Simple you are looping one too many times.
for (i;i<=res.items.length;i++){
^^
arrays are zero index so that means that last index is the length minus one.
for (i;i<res.items.length;i++){
^^

Categories

Resources