【发布时间】:2019-02-25 10:36:21
【问题描述】:
我的用例。
- 我在浏览器中将 5 张图片上传到 s3 服务器并获取该图片上传的 url。
- 将该网址传递给后端。
这是我的异步函数
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 循环。 我怎样才能实现这种异步等待机制?
【问题讨论】:
-
最好使用递归函数而不是循环。所以你可以让它同步。内部函数完成后,就可以解析主函数了。
-
你知道异步不是非阻塞的吗?它只是延迟了一些代码的执行,但如果该代码需要一段时间,它会在启动时阻塞。
标签: javascript ecmascript-6 async-await