javascript - 如何在 javascript 中使用 async await 等到 for 循环完成?
问题描述
我的用例。
- 我在浏览器中将 5 张图片上传到 s3 服务器并获取图片上传的网址。
- 将该网址传递到后端。
这是我的异步功能
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 循环。我怎样才能实现这种异步等待机制?
解决方案
" 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;
}
}
}
推荐阅读
- java - 用户登录时登录和将用户信息读入文本字段的问题
- android - 在使用 RX 和改造 Android 时处理 PDF 响应
- java - JavaFx - 如果值都相同,如何获取按钮数组索引
- kotlin-native - Tensorflow Kotlin/Native 在'中找不到'main'
' 包裹 - javascript - 将 HTTP 预加载与 EventSource/Server 发送事件一起使用?
- c# - 在 C# 项目中是否有存储重要数据的文件?
- php - 创建和填充变量变量的值
- javascript - 在 HTML5 画布上动画绘制路径
- powershell - 如何从 Powershell 打印到 csv?
- python - 如何从图像创建视频?