node.js - 通过咖啡脚本中的承诺和循环避免内存泄漏(无等待)
问题描述
我目前正在尝试在循环中使用 Promise 执行一些操作,但最终导致了巨大的内存泄漏。
我的问题正是本文中指出的问题,但与作者相反,我用的是咖啡脚本(是的,带有连字符。这意味着咖啡脚本 1.12,而不是最新版本)。因此,我无法使用“await”关键字(这是一个随意的猜测,因为每次我想使用它时,都会出现“await is not defined”错误)。
这是我的原始代码(内存泄漏):
recursiveFunction: (next = _.noop) ->
_data = @getSomeData()
functionWithPromise(_data).then (_enrichedData) =>
@doStuffWithEnrichedData(_enrichedData)
@recursiveFunction()
.catch (_err) =>
@log.error _err.message
@recursiveFunction()
所以根据我链接的文章,我必须做这样的事情:
recursiveFunction: (next = _.noop) ->
_data = @getSomeData()
_enrichedData = await functionWithPromise(_data)
@recursiveFunction()
但话又说回来,我被卡住了,因为我不能使用“等待”关键字。那么最好的方法是什么?
编辑:
这是我真正的原始代码。我想要实现的是一个人脸检测应用程序。这个函数位于一个库中,我正在使用“服务”变量来公开库之间的变量。为了从网络摄像头获取帧,我使用的是 opencv4nodejs。
faceapi = require('face-api.js')
tfjs = require('@tensorflow/tfjs-node')
(...)
# Analyse the new frame
analyseFrame: (next = _.noop) ->
# Skip if not capturing
return unless Service.isCapturing
# get frame
_frame = Service.videoCapture.getFrame()
# get frame date, and
@currentFrameTime = Date.now()
# clear old faces in history
@refreshFaceHistory(@currentFrameTime)
#convert frame to a tensor
try
_data = new Uint8Array(_frame.cvtColor(cv.COLOR_BGR2RGB).getData().buffer)
_tensorFrame = tfjs.tensor3d(_data, [_frame.rows, _frame.cols, 3])
catch _err
@log.error "Error instantiating tensor !!!"
@log.error _err.message
# find faces on frames
faceapi.detectAllFaces(_tensorFrame, @faceDetectionOptions).then (_detectedFaces) =>
@log.debug _detectedFaces
# fill face history with detceted faces
_detectedFaces = @fillFacesHistory(_detectedFaces)
# draw boxes on image
Service.videoCapture.drawFaceBoxes(_frame, _detectedFaces)
# Get partial time
Service.frameDuration = Date.now() - @currentFrameTime
# write latency on image
Service.videoCapture.writeLatency(_frame, Service.frameDuration)
# show image
Service.faceRecoUtils.showImage(_frame)
# Call next
_delayNextFrame = Math.max(0, 1000/@options.fps - Service.frameDuration)
setTimeout =>
# console.log "Next frame : #{_delayNextFrame}ms - TOTAL : #{_frameDuration}ms"
@analyseFrame()
, (_delayNextFrame)
解决方案
解决方案是处理发送到detectFaces 的张量副本。
faceapi.detectAllFaces(_tensorFrame, @faceDetectionOptions).then (_detectedFaces) =>
(...)
_tensorFrame.dispose()
(...)
推荐阅读
- angular - “NullInjectorError:没有 t 的提供者!” @ngrx 出错
- asp.net-core - 是否可以获得特定操作所需的角色?
- flutter - 包装在扩展小部件下时,错误容器小部件没有高度
- facebook - 将域重定向到不符合社区标准 Facebook 的域
- php - 用php防止网站重放攻击的好方法
- node.js - 如何阻止数据:通过 puppeteer 的图像/编码图像请求
- python - tkinter 绑定每个条目
- reactjs - 有没有在 React 中导入多个模块/组件的速记方法?
- flutter - Flutter setState(() 没有更新我的文本值
- javascript - 如何使用 JavaScript 实现淡出效果?