2016-10-01 81 views
3

我有一个数组arr,我需要对它的每个值运行一个函数。但是,数组在循环过程完成数组处理之后进行更新。例如,有1000个用户名,每秒有10个新用户名。同步处理一个数组(它在更新的同时进行处理)

如何在这个不断更新的阵列上运行同步任务?

也可能没有更多的用户名被添加到数组中,所以它应该有一个完成阶段。然后,即使用户名已完成,用户名也可以再次开始进入阵列,因此我还需要处理重新开始的任务。

我在数组元素(用户名)上运行的函数是异步的,IE中有一个setTimeout

+0

你必须有一个处理的阵列和未加工的数组,你将处理未处理数组的最后一个元素,并把它添加到处理的阵列,然后将其删除未处理数组元素。 – Akxe

+0

您正在更新数组的每个值上运行的函数,还是另一个(不相关的)进程?如果是后者,请详细说明。我们在这里谈论什么样的“更新”,你只提到“添加”? – Bergi

+0

即使你正在运行的功能是异步的,这是否甚至重要?如果您在所有项目上同步启动它(以便同时运行1000个异步任务),那么更新有什么问题? – Bergi

回答

0

您可以使用队列来获取等待项目和完整项目的列表。

张贴代码的胆量是

while (this.queue.length) { 
    this.complete.push(this.mapper(this.queue.pop())) 
} 

我们从队列中拉出的最新值,与映射函数修改它,将它添加到完整列表。

class Queue { 
 
    constructor(queue, mapper) { 
 
    this.queue = queue || [] 
 
    this.complete = [] 
 
    this.mapper = mapper 
 
    // start running the stack processing 
 
    this.map() 
 
    } 
 
    // start processing the stack 
 
    map() { 
 
    // loop over the stack until it's empty 
 
    while (this.queue.length) { 
 
     this.complete.push(this.mapper(this.queue.pop())) 
 
    } 
 
    console.log('complete processing', this.complete.length, 'items') 
 
    } 
 
    add(val) { 
 
    console.log('add', val) 
 
    // add value to the stack 
 
    this.queue.unshift(val) 
 
    // run the stack processing 
 
    this.map() 
 
    } 
 
    // get the complete stack 
 
    completed() { 
 
    return this.complete 
 
    } 
 
} 
 

 
// just a random function to modify the stack contents 
 
const toHex = item => { 
 
    const hex = item.toString(16) 
 
    return '0x' + (hex < 10 ? '0' + hex : hex) 
 
} 
 
// instantiate your new stack 
 
const queue = new Queue([1, 2, 3, 4, 5, 6, 7], toHex) 
 

 
// nothing to see here, it's just to mock up the asynchronous adding 
 
// of items to the stack 
 
const startTime = Date.now() 
 

 
const timer =() => { 
 
    const now = Date.now() 
 
    queue.add(now - startTime) 
 
    if (now - startTime < 1000) { 
 
    setTimeout(timer, parseInt(Math.random() * 30)) 
 
    } 
 
} 
 
timer()

+0

你是指堆栈还是队列? – Bergi

+0

可能是一个更好的词 – synthet1c

+0

不,这两个数据结构完全不同。你的意思是? – Bergi