javascript - 使同步代码异步处理大型数组并发出完成百分比

标签 javascript angular typescript rxjs

这似乎不是执行此操作的正确方法,但它确实有效。有没有一种“rxjs”方法可以将同步代码变成异步代码,以便我的观察者可以在我开始处理数据之前返回?我能想到的唯一方法是将流程放在 Promise 中。

@Component({})
export class MyClass {
  public processData() {
    const sub = new BehaviorSubject<number>(0)
    new Promise(() => {
      let c = 0
      let completionPercentage = 0
      for (let x = 0; x < width; x++) {
        for (let y = 0; y < height; y++, c++) {
          // Do some calculations
          // Then compute completion percentage
          sub.next(completionPercentage)
        }
      }
    })
    return sub.asObservable()
  }
}

最佳答案

首先,您当然不应该那样做...并将计算移至 BE 或 service worker。

但如果你这样做了——你应该使用 setTimeout/setInterval 而不是卡住你的 UI。您进行迭代,而不是让 Angular 检测更改,然后调用另一个迭代。

@Component({
  selector: 'my-app',
  // Most of time browser is busy, though you can click button and see that UI somehow responds
  template: '<button (click)="x = x + 1">test me</button>{{x}}<div *ngFor="let r of results">{{r}}</div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  executor = new Executor();
  results = [];
  x = 0;

  ngOnInit(){
    this.executor.subject.subscribe(value => {
      this.results.push(value);
    })
    this.executor.run();
  }

}

class Executor {
  currentRun = 0;
  maxRuns = 1000;
  subject = new Subject();

  run() {
      const r = this.multiply(this.currentRun, this.currentRun);

      this.subject.next(r);
      this.currentRun++;

      if (this.currentRun < this.maxRuns) {
        setTimeout(() => this.run());
      }
  }

   multiply(a, b) {
     const t = new Date().getTime();
     let r = 0;
     for (let i = 0; i < a + 20000; i++) {
       for (let j = 0; j < b + 30000; j++) {
         r++;
       }
     }
     console.log('spent: ' + (new Date().getTime() - t), a, b); // for this time browser is frozen ~ 200-300 ms
     return r;
   }
}

关于javascript - 使同步代码异步处理大型数组并发出完成百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63984010/

相关文章:

javascript - 从 Angular2 访问 HTML5 本地存储

javascript - 如何在 typescript 中添加扩展泛型类的构造函数?

javascript - 使用 Meteor 中的事件从数组中检索元素

javascript - 如下所示的这段 php 代码有什么问题?

javascript - Angular - 如果数组中存在值,则禁用选择选项

javascript - 如何在 typescript 中初始化构造函数中的常量字段?

Javascript 命名约定 : value() vs getValue()

javascript - raphael.js 中的拖动约束和缩放

Angular 2 ng bootstrap typeahead 传递附加参数

javascript - 捕获后如何重试?