node.js - 如何在 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 仅在异步函数中有效
解决方案
您需要添加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);
推荐阅读
- rx-java2 - Micronaut/RxJava 控制器不向客户端返回输出
- javascript - replaceAll 不带替换 html 标签 JavaScript
- vba - 在 Powerpoint 中查找和删除文本
- ansible - 如何根据条件设置不同的参数
- stata - Stata:如何从病例对照研究的结果中生成数据集?
- ruby-on-rails - 除了名称属性之外,是否可以使用机械化复选框?
- python - 无法安装 pytorch:没有为 torch==1.7.0+cpu 找到匹配的发行版
- unity3d - 内置摄像头上的鼠标位置
- azure-cosmosdb - 带有 cosmos db 的 Asp.net 核心 api 中的 Json 补丁
- javascript - 制作状态机的承诺链?