【问题标题】:DynamoDB batchWrite not awaiting before moving on, and no errors?DynamoDB batchWrite 在继续之前没有等待,并且没有错误?
【发布时间】:2021-05-19 12:19:14
【问题描述】:

我有一个 lambda,它预计会遍历扫描的项目,在 25 个项目批次中对每个项目进行批处理,从这些项目创建一个 DeleteRequest 并使用 Dynamo 的 .batchWrite() 方法删除它们。

我在使用 DynamoDB 的 dynamoDb.batchWrite({ RequestItems: requestItems }).promise() 方法时遇到了问题,在移动到我的一批 25 循环的下一次迭代之前,它似乎永远不会完成。我认为这是我的 async/await 的问题,但是,我似乎无法发现它!

这个 lambda 运行的输出如下:

我有一个扫描项目的方法:

async function getAllItemsFromTable (TableName) {
  const res = await dynamoDb.scan({ TableName }).promise()
  return res.Items
}

批处理功能(因此每个请求针对 25 个项目,以满足要求):

function batch(array, size) {
  const chunked_arr = []
  let index = 0
  while (index < array.length) {
    chunked_arr.push(array.slice(index, size + index))
    index += size
  }
  return chunked_arr
}

删除函数(通过写入 Dynamo 来处理这些批次):

async function deleteAllItemsFromTable (items) {
  let numItemsDeleted = 0
  const batchedArr = batch(items, 25)

  batchedArr.forEach(async (chunk) => {
    const requestItems = {
      [tableName]: chunk.map((item) => {
        numItemsDeleted++
        const Key = { id: item.id }
        return { DeleteRequest: { Key } }
      }),
    }
    
    if (requestItems[tableName].length > 0) {
      console.log("requestItems", requestItems)
      try {
        console.log("Starting Batch Write..") // this prints.
        // this line below NEVER finishes. It also doesn't spit any errors out. I'm awaiting, what else?
        await dynamoDb.batchWrite({ RequestItems: requestItems }).promise()
        console.log("Finished Batch Write..") // this doesn't ever print.
      } catch (error) {
        console.log("Error: ", error) // this doesn't ever print.
      }
    }
  })

  console.log("numItemsDeleted", numItemsDeleted) // this prints.
  return { numItemsDeleted }
}

最后,我像这样运行我的 lambda:

const items = await getAllItemsFromTable(tableName)
const { numItemsDeleted } = await deleteAllItemsFromTable(items)
console.log(`--- ${numItemsDeleted} items deleted`)

【问题讨论】:

  • 嘿 CeraMix,请向我们展示 Lambda 的输出作为代码块中的文本 - 这使得搜索引擎更容易阅读和索引 :-)

标签: javascript amazon-web-services aws-lambda amazon-dynamodb serverless


【解决方案1】:

问题是您永远不会等待批处理列表循环执行。您开始所有执行,然后移至下一行。所以你最终永远不会等待处决。

变化:

batchedArr.forEach(async (chunk) => {...})

await Promise.all(batchedArr.map(async (chunk) => {...})))

【讨论】:

    猜你喜欢
    • 2016-12-27
    • 2021-12-09
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多