【发布时间】:2021-11-27 07:49:48
【问题描述】:
我正在使用拖放文件上传多张图片。
如何使用异步等待来上传图片,因为我想将参数发送到从第一个请求返回的下一张图片。
从第一个请求返回的post_id 应该与所有下一个图像一起发送。
这是正在做的事情,但它没有等待:
dropped(files: NgxFileDropEntry[]) {
this.files = files;
for (const droppedFile of files) {
// Is it a file?
if (droppedFile.fileEntry.isFile) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file(async (file: File) => {
// Here you can access the real file
console.log(droppedFile.relativePath, file);
await new Promise((resolve, reject) => {
this.http.uploadImages(file, 'UploadImage', this.postId).subscribe((res: any) => {
if (res.status == true) {
resolve(true);
this.postId = res.data.post_id; // i want to send this ID in next request.
} else {
reject();
console.log(res.message);
}
})
});
});
} else {
// It was a directory (empty directories are added, otherwise only files)
const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
console.log(droppedFile.relativePath, fileEntry);
}
}
}
【问题讨论】:
-
您同时启动所有 Promise,尝试使用调试器运行它或放置控制台日志以检查发生了什么。您可以尝试在循环之外提取第一个调用,然后将 id 传递给循环中的其余调用。
-
使用调试器可以按预期工作。以及所有使用 id 发送的下一个呼叫。但没有调试器不工作
标签: javascript angular typescript file-upload async-await