我有一个数组,我在其中推送对象,我正在使用 array.unshift(object)
将对象添加到数组的开头。
我正在使用 var object = array.pop()
从数组中检索元素,这是从数组末尾删除对象。
现在我的数组被填充得非常快,这个数组中的多个对象每秒都被推送。每次将新元素插入数组时,我都需要弹出数组并对其进行处理并进一步发送,这需要时间。
那么每次间隔1秒调用一个方法然后从数组中弹出一个元素并处理它是不是一个好方法,但是如果从数组中处理对象需要超过1秒,那么next对 process 方法的调用也应该被延迟,简而言之,process 数组方法应该在每个间隔后调用,但如果之前的调用仍在处理中,则应该等待。
什么是更好的实现方式?
示例代码:
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
}
});
最佳答案
在我看来,您正在实现一个队列。您希望能够推到队列的后面 (unshift
),这可能会很快发生。您还想处理队列前面的项目 (pop
),但处理阶段需要时间。我的猜测是这些进程是异步运行的,因此您最终会同时发生许多处理步骤,并且会遇到一些类似数据竞争的情况。
除非您需要主动检查队列中的内容(在您的处理函数之外),否则我建议一起删除队列,并使用 promise 链代替队列。
为此,无论何时触发传入数据事件,您都无需使用 unshift()
,只需将数据传递到您的 promise 链,该 promise 链将在所有先前处理完成之前执行。一些伪js:
// the promise chain (initialised to automatically trigger then())
var worker = Promise.resolve();
// handle incoming data
function incomingData(data){
// process this data AFTER all other processing and update the chain
worker = worker.then(last => processData(data));
}
// process data
function processData(data){
// do work on the data and return a promise if work is async
return ...
}
更新:我建议的第一件事是阅读 Promises .但我会在下面做更深入的解释:
设置工作器。通过将变量设置为
Promise.resolve()
,您实质上是在创建一个已经解决(已完成)的 promise 。将其视为一个空队列,它已经完成了它需要做的所有工作。当您获得新的传入数据时更新 promise 链。如果你在 then 中放置一个函数,比如
myPromise.then(myFunc)
,myFunc 将不会运行,直到myPromise
被解析,这取决于程序员。它可能会在某些 api 调用返回后或在其他一些工作后得到解决。你可以这样想对 worker 的更新:想象每次新数据到达时运行
processData(data)
,传递接收到的data
。现在想象在前一个函数完成之前无法运行该函数。这就是上面代码中发生的事情。所以是的,传入的数据已存储。
关于javascript - 使用 unshift 和 pop 序列处理对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39738229/