2016-11-23 1 views
0

전체 배열을 인쇄 할 때 print.but 요소로 인쇄하려고하면 정의되지 않은 것으로 인쇄됩니다. 이것은 내 기능입니다. function.client 함수의 끝에 배열을 인쇄합니다. API 함수는 ajax 함수를 통해 데이터베이스의 특정 문자열과 일치하는 정수 ID를 얻고 두 배열에 밀어 넣으려고했습니다. 심지어 전화가 완료되지 않은 다음 행으로 작업을 계속할 것 의미자바 스크립트 배열이 정의되지 않음

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.

+0

위의 코드 중 어떤 부분이 작동하지 않습니까? – Joe

+0

정의되지 않은 배열과 배열을 포함하여 모든 결과를 표시 할 수 있습니까? – Aks

+0

코드 끝에 정의되지 않은 배열에 주석을 달았습니다. –

답변

1

귀하의 API 호출이 비동기입니다.

console.log이 아직 존재하지 않기 때문에 undefined이 표시됩니다. arrayForClass은 그 순간에 비어 있으므로 arrayForClass [0]은 존재하지 않습니다. 기존 변수에 console.log, 심지어 순간에 비어 있지만, 디버거 도구는 데이터에 왔을 때 콘솔에 당신을 위해 그것을 업데이트로 스마트려고 노력하기 때문에

다음 줄은 올바른 결과를 얻을.

당신이 필요로 차리 같은 콘솔에서 데이터를 얻을 이유

console.log(JSON.parse(JSON.stringify(arrayForClass))); 

이는 설명한다 : 당신이 정말 그 시점에서 실제 값을보고 싶다면

, 당신은 예를 들어, 어떻게 든 불변해야 해당 변수를 사용하려면 각 호출과 관련하여 해당 콜백 함수 내부에서 수행해야합니다.

+0

다른 함수에서 이러한 배열을 사용하려면 어떻게해야합니까? –

+0

내가 말했듯이, 함수는 콜백 함수 내부에서 호출되어야합니다. async-callback에 대한 아이디어를 얻으려면이 스레드를 읽을 수 있습니다 : http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. – Hereblur

관련 문제