【发布时间】:2016-09-28 04:45:33
【问题描述】:
我有一个要在其中推送对象的数组,我正在使用array.unshift(object) 将对象添加到数组的开头。
我正在使用 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:是的,我会保证,但问题是在完成处理之前调用了相同的方法。
-
@Matt Way:我需要等待几秒钟,以防我要处理的数组可能为空并且调用递归(再次使用相同的方法)可能会产生问题,并且它可能会进入无限循环。
标签: javascript angularjs arrays