node.js - NodeJS 将文件写入 AWS S3 - Promise.All with async/await 不等待

标签 node.js amazon-web-services amazon-s3

我使用 NodeJS 将许多文件写入 AWS S3。我在一个 stringifed 变量中有数据,但也测试了在文件中的读取。文件成功写入 S3,因此它确实可以工作,但“await Promise.all()”在文件上传完成之前完成。我需要知道文件何时完成上传。

    // Stream File Data to S3
    const data = "blah blah blah"
    const s3Path = "my_path"
    const promises = []
    promises.push(uploadFile(data, `${s3Path}/1111.xml`))
    promises.push(uploadFile(data, `${s3Path}/2222.xml`))
    promises.push(uploadFile(data, `${s3Path}/3333.xml`))
    promises.push(uploadFile(data, `${s3Path}/4444.xml`))
    const completed = await Promise.all(promises)

下面是我用来上传文件的函数。

const uploadFile = (data, key) => {

     // const fileContent = data
    const fileContent = fs.readFileSync("/full_path/test.xml")

    // Setting up S3 upload parameters
    const params = {
        "Bucket": "my_bucket",
        "Key": key,
        "ContentType": "application/xml",
        "Body": fileContent
    }

    // Uploading files to the bucket
    s3.upload(params, (err, data2) => {
        if (err) {
            throw err
        }
        console.log(`File uploaded successfully. ${data2.Location}`)
        return true
    })
}

有没有办法更新这个,让 promise.all() 在继续之前等待所有上传完成?

谢谢

最佳答案

那是因为 uploadFile() 没有返回 promise 。而且,Promise.all() 只有在您向它传递一组与其异步操作相关联的 promise 时才会做一些有用的事情。

我怀疑 s3.upload() 有一个您应该使用的 promise 接口(interface)。

const uploadFile = async (data, key) => {

    const fileContent = await fs.promises.readFile("/full_path/test.xml");

    // Setting up S3 upload parameters
    const params = {
        "Bucket": "my_bucket",
        "Key": key,
        "ContentType": "application/xml",
        "Body": fileContent
    }

    // Uploading files to the bucket
    const data2 = await s3.upload(params).promise();
    console.log(`File uploaded successfully. ${data2.Location}`);
    return true;
}

现在 uploadFile() 返回一个 promise,该 promise 在其中的异步操作完成时解析(或者如果有错误则拒绝)。因此,当您将 uploadFile() 的结果推送到一个数组并将其传递给 Promise.all() 时,它将能够告诉您它们何时全部完成完成。


仅供引用,如果 uploadFile() 每次总是读取相同的文件内容,那么您应该在函数外部读取一次,也许将数据传递给 uploadFile() .


仅供引用,这里有一些 AWS doc关于在 Javascript 界面中使用 promises。值得一读。

关于node.js - NodeJS 将文件写入 AWS S3 - Promise.All with async/await 不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66404410/

相关文章:

javascript - 如何在node.js上使用邮戳电子邮件?

postgresql - 允许您在 SELECT 语句中引用别名列的 PostgreSQL 函数叫什么?

amazon-web-services - 如何将 AWS ELB 上的 SSL 终止到 Flask App?

ssl - AWS SSL 安装但不工作

javascript - 如何将 JSON 的特定部分转换为字符串?

javascript - 将 Promises 与 mongoose 一起使用的正确方法是什么?

ruby-on-rails - Carrierwave/Fog - 参数错误,无法识别提供者

ruby-on-rails - Carrierwave Direct gem 上传成功后没有重定向?

amazon-web-services - 连接到 S3 存储桶时如何保护 AWS 中的凭证

javascript - 如何在 Dynamodb 中存储对象?