通过promise和循环咖啡脚本(无等待)避免内存泄漏



我目前正试图在循环中使用promise执行一些操作,但最终出现了巨大的内存泄漏。

我的问题正是本文中指出的问题,但与作者相反,我是用咖啡脚本(是的,带连字符。这意味着咖啡脚本1.12,而不是最新版本)写作的。因此,我无法使用"等待"关键字(这是一个偶然的猜测,因为每次我想使用它时,我都会得到"等待未定义"的错误)。

这是我的原始代码(内存泄漏):

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()

但话说回来,我被卡住了,因为我不会用"等待"这个关键词。那么最好的方法是什么?

编辑:

这是我真正的原始代码。我正在努力实现的是一个人脸检测应用程序。这个函数位于库中,我使用"Service"变量在库之间公开变量。为了从网络摄像头获取帧,我使用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()
(...)

最新更新