测量外部API调用的时间:以角度处理异步

时间:2019-06-12 11:21:40

标签: angular asynchronous

我只需要一个简单的角度应用程序即可调用外部API(获取请求)并测量应用程序需要多长时间来获取数据。

我的代码如下:

  measureData(): {
    this.t0 = performance.now();

    this.errors = '';

    this.getHello().subscribe(
      (result: string) =>
        {
          this.text = result
          console.log("test")
          return this.text
        },
        error => {
          this.errors = error.message
          console.log(error.message)
          return this.errors
        }
    )
    this.t1 = performance.now();
    this.test = this.t1 - this.t0;
    console.log("Action took " + this.test + " milliseconds.")
    this.times.push(this.test);
  }  

在这种情况下,我会遇到异步问题。所以我尝试了这个:

main(){
    this.measureData().subscribe(
      (result: String) => {
        this.measurePerformance();
      }
    )
  }

  measureData(): Observable<any> {
    this.t0 = performance.now();

    this.errors = '';

    this.getHello().subscribe(
      (result: string) =>
        {
          this.text = result
          console.log("test")
          return this.text
        },
        error => {
          this.errors = error.message
          console.log(error.message)
          return this.errors
        }
    )
    return 
  }  

  measurePerformance() {
    this.t1 = performance.now();
    this.test = this.t1 - this.t0;
    console.log("Action took " + this.test + " milliseconds.")
    this.times.push(this.test);
  }

在这种情况下,我会收到此错误:

ERROR TypeError: Cannot read property 'subscribe' of undefined

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法测量经过的时间:

var start = new Date().getTime();

// Your code

var end = new Date().getTime();

var elapsedTime = end -start;

console.log("Time", elapsedTime );

答案 1 :(得分:0)

对于我的解决方案,我使用了await delay(500)

const delay = ms => new Promise(res => setTimeout(res, ms));

我的完整代码:

async measureData() {

   this.errors = '';
   const delay = ms => new Promise(res => setTimeout(res, ms));

   for (let i = 0; i < this.numberMeasurements; i++) {
     this.t0 = performance.now();
     this.getHello().subscribe(
       (result: string) => {
         this.text = result
         this.t1 = performance.now();
         this.test = this.t1 - this.t0;
         console.log("Action took " + this.test + " milliseconds.")
         this.times.push(this.test);
         console.log(result)
       },
       error => {
         this.errors = error.message
         console.log(error.message)
       }
     )
     await delay(500);
   }

 }