객체를 푸시 (push)하는 배열이 있는데 배열의 처음에 객체를 추가하려면 array.unshift(object)
을 사용하고 있습니다.unshift 및 pop 시퀀스를 사용하는 객체 배열 처리
배열 끝에있는 객체를 제거하고있는 var object = array.pop()
을 사용하여 배열에서 요소를 가져옵니다.
이제 내 배열이 매우 빠르게 채워지고 있습니다.이 배열의 여러 객체가 매초마다 푸시됩니다. 새 요소가 배열에 푸시 될 때마다 배열을 팝하여 처리하고 추가로 보내야합니다. 시간이 걸립니다.
매번 1 초 간격으로 메소드를 호출 한 다음 배열에서 하나의 요소를 팝하여 처리하는 것이 좋은 방법이지만, 배열에서 객체를 처리하는 데 1 초 이상 걸리면 프로세스 메서드에 대한 다음 호출도 지연되어야합니다. 짧은 프로세스 배열 메서드는 모든 간격 후에 호출되어야하지만 이전 호출이 아직 처리 중이면 기다려야합니다.
더 나은 구현 방법은 무엇입니까?
샘플 코드는 : 당신이 큐를 구현 같은
angular.module('myApp')
.service('DataService', ['$rootScope', 'UpdateService', function($rootScope, UpdateService)
{
// To store array of JSON updates
var arrayOfUpdates = [];
// To store callbacks to which we need to send updates after processing
var arrayofCallbacks = [];
// Method is getting called when there are updates from "UpdateService" server
this.onDataUpdated = function (jsonObj)
{
// This will add this object in the array
arrayOfUpdates.unshift(jsonObj);
}
// This method will process data and send it further
function processData()
{
// Get the last element from the array
var jsonObj = arrayOfUpdates.pop();
// Now process this JSON data
var data = doSomeCalculations(jsonObj);
// There can be 10-20 callbacks at a time
for(var index=0;index<arrayofCallbacks.length;index++)
{
var object = arrayofCallbacks[index];
object.onUpdatedData(data);
}
// After this pop next element and process and send to registered callbacks
// I can not call "processData()" again as it can create loop
// Also calling it after interval might call it when it has not completed processing
}
});
약속하셨습니까? – cracker
조금 더 자세히 설명해 주시겠습니까? 이 배열은 어떻게 채워 집니까? 어떤 유형의 가공을하고 있습니까? 좀 더 구체적 일수록 도움이됩니다. 또한 더 많은 코드를 추가 할 수 있다면 도움이 될 것입니다 – wilsotobianco
왜 다음 항목을 처리하기 전에 잠깐 기다려야합니까? –