Async/await 不使用 AWS S3 Node.js SDK

Async/await Not working with AWS S3 Node.js SDK

我创建了一个非常 short/simple 的问题示例,说明我在使用 Node.js 的 aws-sdk 程序包的脚本中遇到 Promises 问题。

简而言之,脚本是而不是等待await关键字。它在循环中循环而不等待 async 函数在继续之前成功完成。

代码示例:


main.js

const AWS = require('aws-sdk')
import constants from '@/constants'

AWS.config.update({
  accessKeyId: constants.awsAccessKey,
  secretAccessKey: constants.awsSecretAccessKey,
  region: constants.awsRegion
})

export const s3 = new AWS.S3({apiVersion: '2006-03-01'})

单击某个按钮并触发 testS3() 方法...


testActions.js

import { s3 } from '@/main.js'

export async function testS3 () {
  const testParams = {
    Bucket: AWS_BUCKET,
    Key: `test_file.txt`,
    Body: 'Testing stuff'
  }

  async function testFunction(layer) {
    console.log('in prepare design 1')
    const result = await s3.putObject(testParams).promise()
    console.log(`the results: ${result}`)
  }

  [1,2,3].forEach(async (x) => {
    const result = await testFunction()
  })
}

调试器的输出:


我原以为消息会交错,如果您遵循逻辑流程,这是有意义的。

应该是in prepare design 1,然后然后显示the results...,然后再做2次。

立即显示 in prepare design 1 三次的输出告诉我循环在继续之前没有等待函数。


我是否在某些方面设置了 async/await 错误?我已经尝试了多次不同的迭代,但似乎无法按照我的预期进行。

显示的行为是正确的,因为 forEach 的处理程序也是一个 async 函数:

  async (x) => {
    const result = await testFunction()
  }

所以 forEach 循环将立即 运行 3 个异步函数。这些函数中的每一个都将 await 异步地用于承诺链的其余部分。

如果要同步执行,使用普通的for循环:

for(var i=0; i<3; i++){
  const result = await testFunction()
}

这是对 AVAVT 答案的补充(因为我无法对此发表评论),您也可以这样做,这样您就不必手动输入迭代次数并打算使用迭代值.

import { s3 } from '@/main.js'

export async function testS3 () {
  const testParams = {
    Bucket: AWS_BUCKET,
    Key: `test_file.txt`,
    Body: 'Testing stuff'
  }

  async function testFunction(layer) {
    console.log('in prepare design 1')
    const result = await s3.putObject(testParams).promise()
    console.log(`the results: ${result}`)
  }

  for (const iterator of [1,2,3]) {
      const result = await testFunction();
  }

}