NodeJS 如何在setTimeout中调用异步函数

lnlaulya  于 2023-01-04  发布在  Node.js
关注(0)|答案(1)|浏览(178)

我们有一个ASYNC FUNCTION,它可以进行屏幕截图。我们现在需要在15秒的间隔内调用此ASYNC FUNCTION五次。我们已经尝试了在node.js中使用SetTimeout、SetInterval和所有延迟等待。我们无法在此SetTimeouts中调用我们的ASYNC FUNCTION。请帮助我们,因为我们不熟悉node.js。

class QnABot extends ActivityHandler{
constructor(logger) {
        super();
this.onMessage(async (context, next) => {                            
              let counter = 0;
              let timer = setInterval(function() {
              console.log('I am an asynchronous message');
              await this.uploadcaptureattachment(context); 
              counter += 1;
              if (counter >= 5) {
                  clearInterval(timer);
              }
            }, 5000);
         });

  }

async uploadcaptureattachment(turnContext) { 
         var screencapture = require('screencapture')
         screencapture(function (err, imagePath) {
      })
        screencapture('D:/output.png', function (err, imagePath) {
      })
  }
}

错误:等待此。上载捕获附件(上下文);^^^^语法错误:await仅在异步函数中有效

mlmc2os5

mlmc2os51#

您需要将async添加到函数中:

setInterval(async function() {
    console.log('I am an asynchronous message');
    await this.uploadcaptureattachment(context); // WE ARE CALLING OUR ASYNC FUNCTION HERE
    counter += 1;
    if (counter >= 5) {
        clearInterval(timer);
    }
}, 5000);

相关问题