angular - 如何等待'for loop next iteration'直到获得 FileReader.onload 结果
问题描述
我们如何处理循环中的异步方法?我在 Angular 程序中遇到问题,我无法处理异步方法。我想等待异步方法。有什么方法可以在 for 循环中等待异步方法。
这是我的代码:
msg: string[] = [];
filePicked() {
this.msg = [];
this.msg.push("file picked");
const file: File = new File([""], "C:\Users\Arun Girivasan\Downloads\about.jpg");
for (var i = 0; i < 10; i++) {
const reader = new FileReader();
reader.onload = () {
this.msg.push("file loaded successfully");
}
reader.readAsDataURL(file);
this.msg.push(i.toString());
}
html:
<div *ngFor="let m of msg">{{m}}</div>
输出:
file picked
0
1
2
3
4
5
6
7
8
9
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
file loaded successfully
我想要像这样的输出:
file picked
file loaded successfully
0
file loaded successfully
1
file loaded successfully
2
file loaded successfully
3
file loaded successfully
4
file loaded successfully
5
file loaded successfully
6
file loaded successfully
7
file loaded successfully
8
file loaded successfully
9
我怎样才能做到这一点?
解决方案
您需要将文件读取器代码提取到另一个函数中并返回一个 Promise 或 Observable。
private readFile(file: File): Observable<string> {
return new Observable(obs => {
const reader = new FileReader();
reader.onload = () => {
obs.next(reader.result as string);
obs.complete();
}
reader.readAsDataURL(file);
});
}
我在https://stackblitz.com/edit/angular-pt3pbv上准备了一个带有 Observable 的快速示例
推荐阅读
- laravel - 一次性将信息存储到 order 和 order_details 表中
- java - 依赖项没有从导入的 jar 文件反映到我的 Spring Boot 项目中
- android - 预期为 BEGIN_OBJECT,但在路径 $[0] 处是字符串
- kubernetes - Kubernetes 容器运行时网络未准备好
- python - 在 Numpy 中计算累积标准差
- tcl - 将二进制数据变量转换为字节列表
- firebase - 如何使用带有自定义 URL 方案的动态链接?
- vhdl - GHDL -- 具有电路延迟时间的 VHDL 仿真
- java - java构造函数是静态的吗?
- laravel - Lumen 8.2 混合内容问题与招摇资产网址 - Heroku