【问题标题】:Modifying value of object before pushing to promise array in PouchDB/Benchmark.js在推送到 PouchDB/Benchmark.js 中的 Promise 数组之前修改对象的值
【发布时间】:2023-03-25 03:32:02
【问题描述】:

我目前正在测试在 PouchDB 中插入多个不同对象所需的时间,无论是逐个插入它们还是执行批量插入。 我的方法是检索一个生成的大型 JSON 项并在循环中使用自定义函数更改 _id,然后将执行插入操作的函数推送到 promises 数组中以最终调用 Promise。整个阵列。

测试本质上是异步的(需要defer关键字)。

代码看起来像 (coffeescript)

benchmarkCreate: () ->
  result = {}
  Ember.$.getJSON('bigitem.json').then((doc) =>
    @createUpdateTest 10, result, doc[0] # Takes the JSON only
  )

createUpdateTest: (many, res, doc) ->
(@get 'benchSuite').add(new Benchmark("Create #{many} Items Bench",
  'defer': true

  fn: (deferred) =>
    iterations = []
    i = 0
    while i < many
      doc._id = @makeid()
      console.log 'Out of the Promise array: ' + doc._id
      iterations.push ((@get 'pouchService').createUpdateDoc doc)
      i++
    Promise.all(iterations).then((response) ->
      deferred.resolve()
    )
))

pouchService 假定成功插入具有不同 ID 的新项目(无需修订管理)。在将文档放入 PouchDB 之前,我有另一个打印件,我的输出是:

Out of the Promise array: z2sF0
Out of the Promise array: v2J3F
Out of the Promise array: MY2qX    
Out of the Promise array: BkKiv
Out of the Promise array: DjcUK
Out of the Promise array: TIL6e
Out of the Promise array: xjz20
Out of the Promise array: oHAFf
Out of the Promise array: dWK6U
Out of the Promise array: 9KKRi

Inside the Promise Array: 9KKRi
Inside the Promise Array: 9KKRi
Inside the Promise Array: 9KKRi
... X 10

在推入 promise 数组之前,我需要修改 id 10 次,但它似乎只取最后一个值,即使它在推入函数之前打印新值也是如此。

【问题讨论】:

    标签: javascript coffeescript pouchdb benchmark.js


    【解决方案1】:

    我刚刚解决了我自己的问题,以防有人感兴趣。为文档分配新 id 时,它是对象引用正在修改的内容,而不是新对象。解决它:

    docAux = Ember.copy doc
    Object.assign docAux, { _id: @makeid() } # New id for each new item.
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2021-04-30
      相关资源
      最近更新 更多