2016-10-01 85 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