0

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

}

this is the out put.

Dil
  • 307
  • 1
  • 3
  • 15
  • what part of the code above isn't working? – Joe Nov 23 '16 at 09:15
  • can you show us all the result, including undefined and your array. – Aks Nov 23 '16 at 09:25
  • end of the code i have commented the arrays that undefined. – Dil Nov 23 '16 at 09:49
  • What does *prints correctly* look like? – zer00ne Nov 23 '16 at 09:56
  • I'm guessing `client.searchCount` and `client.search` are asynchronous? Just read the part that says `via ajax functions` ... first A in AJAX = asynchronous ... so, ignore the fact that console.log of the arrays seem to show populated arrays, that's a quirk of the console ... if you `console.log(arrayForClass.join())` you'll see it's empty too ... the answer is knowing how to deal with asynchronous code – Jaromanda X Nov 23 '16 at 10:16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jaromanda X Nov 23 '16 at 10:19
  • thanks for the answer.it is very helpfull [Jaromanda X](http://stackoverflow.com/users/5053002/jaromanda-x) – Dil Nov 23 '16 at 11:46
  • if i want to use these arrays in another function.how should I do that? – Dil Nov 23 '16 at 13:21

1 Answers1

1

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.

Hereblur
  • 2,084
  • 1
  • 19
  • 22
  • if i want to use these arrays in another function.how should I do that? – Dil Nov 23 '16 at 13:21
  • Like I said, your function must be called from inside the callback function. may be read this thread to get the idea of async-callback: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. – Hereblur Nov 24 '16 at 02:06