如何使用JavaScript中的async await等到for循环完成?

时间:2018-09-21 04:22:54

标签: javascript ecmascript-6 async-await

我的用例。

  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;
            }
          );
        }
        );
      });
    }

但是它不允许我在resolve函数中使用for循环。 如何实现这种异步等待机制?

1 个答案:

答案 0 :(得分:1)

resolve(FORLOOP) ”-不,那不是它的工作原理。

您应该单独将s3.upload方法推广到一个函数中,该函数将调用该方法并返回结果的承诺,而没有其他结果:

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

现在,您可以在方法中使用它,可以将诺言链接在一起,也可以只使用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;
    }
  }
}
相关问题