首页 > 解决方案 > 通过咖啡脚本中的承诺和循环避免内存泄漏(无等待)

问题描述

我目前正在尝试在循环中使用 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)

标签: node.jscoffeescript

解决方案


解决方案是处理发送到detectFaces 的张量副本。

faceapi.detectAllFaces(_tensorFrame, @faceDetectionOptions).then (_detectedFaces) =>
    (...)
    _tensorFrame.dispose()
    (...)

推荐阅读