首页 > 解决方案 > 如何在 setTimeout 中调用异步函数

问题描述

我们有一个 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); // WE ARE CALLING OUR ASYNC FUNCTION HERE
              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) {
      })
}
}

错误:等待this.uploadcaptureattachment(上下文);^^^^^ SyntaxError: await 仅在异步函数中有效

标签: node.js

解决方案


您需要添加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);

推荐阅读