首页 > 解决方案 > 当我们调用函数时读取文件给出未定义的值,因为没有返回值

问题描述

我附上了代码片段,并输出: 主要目标是处理特定路径中的图像并从模型中生成张量值以显示它。首先调用checkViolence () 并传入路径:

checkViolence = async (path) => {
  const tf = require("@tensorflow/tfjs");
  const tfn = require("@tensorflow/tfjs-node");
  const handler = tfn.io.fileSystem("./model1/model.json");
  try {
    let value = {};
    const model = await tf.loadLayersModel(handler);
    sharp(path)
      .resize({ height: 224, width: 224 })
      .jpeg()
      .toFile(path + " forChecking.jpg", async (err, data) => {
        if (err) throw err;
        console.log(data);
        let s = await processData(path + " forChecking.jpg", model, tfn);
        console.log("processedData:", s);
      });
    // console.log(value);
  } catch (e) {
    console.log(e);
  }
};

里面我们调用processData ()来处理图片,如下图:

processData = async (path, model, tfn) => {
  let val = fs.promises
    .readFile(path, async (err, data) => {
      if (err) throw err;
    })
    .then((data) => {
      console.log("data:", data);
      let tensor = tfn.node.decodeJpeg(data).expandDims(0);
      let output = model.predict(tensor);
      const values = output.dataSync();
      const array1 = Array.from(values);
      console.log("in function", array1[0]);
      return array1[0]; // This value needs to be returned, can be seen in the output of previous line.
    })
  return val;
};

输出:

[0] in function 0.06445053219795227
[0] {
[0] format: 'jpeg',
[0] width: 224,
[0] height: 224,
[0] channels: 3,
[0] premultiplied: false,
[0] size: 6256
[0] }
[0] processedData: undefined
[0] data: <Buffer ff d8 ff db 00 43 00 06 04 05 06 05 04 06 06 05 06 07 07 06 08 0a 10 0a 0a 09 09 0a 14 0e 0f 0c 10 17 14 18 18 17 14 16 16 1a 1d 25 1f 1a 1b 23 1c 16 ... 6206 more bytes>
[0] in function 0.06445053219795227

附言。尝试过 fs.readFile 和 fs.readFileSync 都呈现相同的结果..

请帮助我,async/await 的新手 :(

标签: javascriptnode.jsasync-awaitpromisefs

解决方案


推荐阅读