0

我是 Reactjs 的新手。我创建了一个应用程序来将多个文件上传到 aws s3。我正在使用循环上传所有文件。我还需要从上传的文件中获取响应,例如文件名。这是我到目前为止所拥有的:

const handleClick =  async (event) => {
event.preventDefault();
let newArr = fileInput.current.files;
for (let i = 0; i < newArr.length; i++) {
  const file = newArr[i]
  let newFileName = file.name.replace(/\..+$/, "");
  const ReactS3Client = new S3(config);
  ReactS3Client.uploadFile(file, newFileName).then((data) => {
    if (data.status === 204) {
      console.log( data.key);
    } else {
      console.log("fail");
    }
  });
}

  };

经过大量的谷歌搜索后,我将异步添加到我的 handleclick。我超级困惑。谁能告诉我如何等待循环完成?或者只是等待 handClick 完全执行?如果我尝试将其打印出来,我的密钥也会显示未定义。我只能在handleUpload 中的.then 中得到响应。但是我需要等待所有键才能进行另一个 api 调用和更改页面。任何帮助表示赞赏。

4

1 回答 1

1

首先,您以错误的方式执行此操作。ReactS3Client (在您的情况下)应该初始化一次。

关于你问的问题。你可以使用 Promise.all()。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

像这样使用它。

// Import from other file like config
const ReactS3Client = new S3(config);

const handleClick = async (event) => {
  event.preventDefault();
  try {
    const newArr = fileInput.current.files;
    const v = await Promise.all(
      newArr.map(async (file) => {
        let newFileName = file.name.replace(/\..+$/, "");
        // assuming key is there in response
        const { key } = await ReactS3Client.uploadFile(file, newFileName);
        return {
          newFileName,
          fileKey: key,
        };
      })
    );
    console.log(v);
  } catch (e) {
    console.error(e);
  }
};
于 2021-09-18T17:20:47.000 回答