简体   繁体   English

有没有办法计算异步函数被调用的次数?

[英]Is there a way count how many times an async function is called?

I have function that uploads files from an array of data links我有从数据链接数组上传文件的功能

What I would like to do is if data links array contains 3 files我想做的是如果数据链接数组包含 3 个文件

const testLinks = 3; and async uploadImageData is fired three times I would like to console.log after uploadImageData is fired three times.并且async uploadImageData被触发了三次我想在uploadImageData被触发三次之后console.log

I am thinking of doing a count but all my testing has the count starting over everytime uploadImageData is fired.我正在考虑进行计数,但每次uploadImageData被触发时,我的所有测试都会重新开始计数。

.ts .ts

async uploadImageData(formData: FormData) {
  const testLinks = 3;
  const uploadlink = answerAtachmentUrl;
  const headers = headerLink;
  const loading = await this.loadingController.create({
    message: 'Uploading Photos and Files...',
  });
  await loading.present();
  this.httpClient.post<any>( uploadlink + this.userToken, formData, 
  { 'headers':headers }
    ).pipe(
      finalize(() => { loading.dismiss();})
    )
    .subscribe(res => {
      if (res['success']) {
        setTimeout(() => { this.DeleteAllFiles(); }, 5000);
        this.presentToastPhoto('Photo sync success.');
      } else {
        this.presentToastPhoto('Photo upload failed.');
        let respFail = JSON.stringify(res);
        console.log("respFail", respFail);
      }
    });
    // console.log fires once after count and const testLinks both equal 3
}

"I am thinking of doing a count but all my testing has the count starting over evertime uploadImageData is fired." “我正在考虑进行计数,但我所有的测试都从每次上传图像数据被触发时开始计数。” you didn't post what you tried but you probably did not make the counter a global variable.您没有发布您尝试过的内容,但您可能没有将计数器设为全局变量。 Your code is clearly part of a larger project so I just made this small test to show that it works with async functions.你的代码显然是一个更大项目的一部分,所以我只是做了这个小测试来证明它可以与异步函数一起使用。 If it doesn't work, let me know.如果它不起作用,请告诉我。

 var count=0; async function uploadImageData() { const testLinks = 3; count++; console.log(count); if (count === 3){ console.log('count = 3'); } } uploadImageData(); uploadImageData(); uploadImageData(); uploadImageData();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM