javascript - 同步处理数组(在处理时更新)

标签 javascript arrays

我有一个数组arr,我需要对其每个值运行一个函数。但是,当循环过程完成处理数组时,数组就会更新。

例如,arr 有 1000 个用户名,每秒有 10 个新用户名。

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

也有可能不再有用户名添加到数组中,因此它应该有一个完成阶段。即使已经完成,用户名也可以再次开始进入数组,因此我还需要处理任务的重新启动。

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

最佳答案

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

发布的代码的核心内容是

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()

关于javascript - 同步处理数组(在处理时更新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809847/

相关文章:

javascript - HTML5 模式下的 Angular-ui 嵌套 View 获取 404 未找到模板文件

asp.net - 如何通过 JavaScript ( JQuery ) 从 HTML 对象中通过 id 获取元素内容

c - 通过 C 中的 for 循环将字母表附加到数组

php - 通过月度分配支付值(value)

php 以两种方式对数组进行排序

java - 如何根据项目的主序列列表对一小部分项目进行排序?

javascript - Screeps:计算 body 的构建成本

javascript - 根据单击的链接显示不同的选项卡

javascript - 正则表达式删除某些字符前后的引号

javascript - 检查 jQuery 数组中的值是否按顺序排列