首页 > 解决方案 > 如何在 javascript 中使用 async await 等到 for 循环完成?

问题描述

我的用例。

  1. 我在浏览器中将 5 张图片上传到 s3 服务器并获取图片上传的网址。
  2. 将该网址传递到后端。

这是我的异步功能

try{
    await uploadImagesToS3(imagesArray);

    await saveUrlsInBackend();

}catch(error){

}

在我的uploadImagesToS3函数中,我正在尝试做这样的事情。

uploadImagesToS3(){
    resolve(FORLOOP)
}

在 for 循环运行 5 次后,我想将其解析为我的主要异步函数。

这是我真正的uploadImagesToS3函数

onUpload(array, albumName) {
      return new Promise((resolve, reject) => {
        resolve(
          for (let index = 0; index < array.length; index++) {
          var files = document.getElementById(array[index]).files;
          if (!files.length) {
            return alert("Please choose a file to upload first.");
          }
          var file = files[0];
          var fileName = file.name;
          var albumPhotosKey = encodeURIComponent(albumName) + "//";

          var photoKey = albumPhotosKey + fileName;
          self;
          s3.upload(
            {
              Key: photoKey,
              Body: file,
              ACL: "public-read"
            },
            (err, data) => {
              if (err) {
                return alert(
                  "There was an error uploading your photo: ",
                  err.message
                );
              }
              // alert("Successfully uploaded photo.");
              this.images[index].image_path = data.Location;
            }
          );
        }
        );
      });
    }

但它不允许我在解析函数中使用 for 循环。我怎样才能实现这种异步等待机制?

标签: javascriptecmascript-6async-await

解决方案


" resolve(FORLOOP)" - 不,这不是它的工作方式。

您应该s3.upload单独承诺该方法,将其放入一个只调用它并返回结果的承诺的函数中,而不是其他任何东西:

function upload(value) {
  return new Promise((resolve, reject) => {
    s3.upload(value, (err, res) => {
      if (err) reject(err);
      else resolve(res);
    });
  });
}

现在你可以在你的方法中使用它,或者通过将 Promise 链接在一起或者简单地使用async/ await

async onUpload(array, albumName) { /*
^^^^^ */
  for (const id of array) {
    const files = document.getElementById(id).files;
    if (!files.length) {
      alert("Please choose a file to upload first.");
      return;
    }
    const file = files[0];
    const albumPhotosKey = encodeURIComponent(albumName) + "//";

    const photoKey = albumPhotosKey + file.name;
    try {
      const data = await upload({
//                 ^^^^^
        Key: photoKey,
        Body: file,
        ACL: "public-read"
      });
      // alert("Successfully uploaded photo.");
      this.images[index].image_path = data.Location;
    } catch(err) {
      alert("There was an error uploading your photo: ", err.message);
      return;
    }
  }
}

推荐阅读