Как дождаться «следующей итерации цикла», пока не будет получен результат FileReader.onload - PullRequest
0 голосов
/ 24 ноября 2018

Как мы можем обрабатывать асинхронные методы в циклах?У меня проблема в программе 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  

Как я могу это сделать?

Ответы [ 2 ]

0 голосов
/ 02 декабря 2018

Мы можем сделать это путем зацикливания кода с помощью нашего собственного пользовательского цикла.
Эта работа для меня:

ngOnInit() {
    this.filePicked();
  }

  filePicked() {
    this.msg = [];
    this.msg.push("file picked");
    const file: File = new File(["abcd"], "C:\Users\Arun Girivasan\Downloads\about.jpg");

    this.customLoop(0, 10, file);
  }
  customLoop(index: number, limit: number, file: File) {
    this.readFileUrl(file, (msg: string) => {
      this.msg.push(msg);
      this.msg.push(index.toString());
      if (index < limit - 1) {
        this.customLoop(++index, limit, file);
      }
    });
  }
  readFileUrl(file: File, callback: (msg: string) => any) {
    const reader = new FileReader();
    reader.onload = (function (f) {
      return function (e) {
        callback("file loaded successfully");
      }
    })(file);
    reader.readAsDataURL(file);
  }
0 голосов
/ 24 ноября 2018

Вам нужно будет извлечь код средства чтения файлов в другую функцию и вернуть 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);
    });
}

Я подготовил быстрый пример с Observable на https://stackblitz.com/edit/angular-pt3pbv

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...