javascript - 当我们调用函数时读取文件给出未定义的值,因为没有返回值
问题描述
我附上了代码片段,并输出: 主要目标是处理特定路径中的图像并从模型中生成张量值以显示它。首先调用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 的新手 :(
解决方案
推荐阅读
- npm - 在 Gulp 中重命名 `dist` 目录后仍在生成它
- html - Python jupyter notebook 转换为 html 后,markdown 的编号消失了
- xpath - 如果主题被 javascript 隐藏,如何获取 XPath
- assembly - 如何在 WinMIPS64 中计算除法的余数
- netlogo - 囚徒困境 N 人迭代程序的进化动力学
- javascript - 如何使用 javascript Geolocation 更改布尔值
- uber-api - Uber API /v1/requests end_latitude 和 end_longitude 不起作用
- debugging - 当系统也有显示适配器时,如何将 Linux 紧急输出到 USB 串行控制台
- java - 检查方法是否需要使用注释和反射的参数
- angular - 类型“FormGroup”上不存在属性“数组”