反应,如何在初始化之前调用一个函数然后阻塞它或任何适当的方式?

Posted

技术标签:

【中文标题】反应,如何在初始化之前调用一个函数然后阻塞它或任何适当的方式?【英文标题】:react, how to call a function inside then block before initializing it or any proper way? 【发布时间】:2021-08-03 17:21:17 【问题描述】:

我已经为我的 react 组件构建了一个带有 face-api.js 的 javascript 函数,它将返回/控制面部检测框的宽度和高度。我在几个地方尝试了 console.log,在模型(人脸识别模型)之前它似乎工作正常。

但是当我为面部检测器编写异步函数来检测面部和控制台时。它给了我错误-

Unhandled rejection(Reference Error): Cannot access 'handledImage' before initialization  

这也是屏幕截图。

不知道怎么解决?

这是我的代码faceDetector.js

import * as faceapi from "face-api.js";

//passing image from my react compoenent
const faceDetector = (image) => 
    const imageRef = image;

    const loadModels = async () => 
       // models are present in public and they are getting loaded
        const MODEL_URL = process.env.PUBLIC_URL + "/models";
        Promise.all([
            faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL),
            faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
            faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
            faceapi.nets.faceExpressionNet.loadFromUri(MODEL_URL)
        ])
             // this is rising the issue. I want to call this function after my models loaded so it can detect face
            .then(handleImage)
            .catch((e) => console.error(e));
    ;
    loadModels();

    // this function should detect the face from imageRef and should console the size of detector
    const handleImage = async () => 
        const detections = await faceapi
            .detectSingleFace(imageRef, new faceapi.TinyFaceDetectorOptions())
        console.log(`Width $detections.box._width and Height $detections.box._height`);
    






export faceDetector

【问题讨论】:

【参考方案1】:

您需要更改函数声明的顺序。你不能在声明之前调用const 变量。

//passing image from my react component
const faceDetector = (image) => 
  const imageRef = image;


  // this function should detect the face from imageRef and should console the size of detector
  const handleImage = async () => 
    const detections = await faceapi
        .detectSingleFace(imageRef, new faceapi.TinyFaceDetectorOptions())
    console.log(`Width $detections.box._width and Height $detections.box._height`);


   const loadModels = async () => 
   // models are present in public and they are getting loaded
    const MODEL_URL = process.env.PUBLIC_URL + "/models";
    Promise.all([
        faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL),
        faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
        faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
        faceapi.nets.faceExpressionNet.loadFromUri(MODEL_URL)
    ])
         // this is rising the issue. I want to call this function after my models loaded so it can detect face
        .then(handleImage)
        .catch((e) => console.error(e));
   ;
   loadModels();



【讨论】:

以上是关于反应,如何在初始化之前调用一个函数然后阻塞它或任何适当的方式?的主要内容,如果未能解决你的问题,请参考以下文章

java网络编程-面试题

从DllMain调用LoadLibrary

如何在反应路由器内的任何路由上调用函数?

功能性反应如何不重置状态?

静态构造函数, 静态成员初始化/调用顺序

I/O 模型详解