【问题标题】:Await keyword not waiting for promise to be fulfilled in NodeJS with ExpressAwait 关键字不等待在 NodeJS 中使用 Express 实现承诺
【发布时间】:2021-06-25 03:51:41
【问题描述】:

我是 javascript 和异步函数的新手,我正在尝试使用 Express 在 NodeJs 中编写一个 API,该 API 从 Postman 获取 JPG 图像并将其放入我的图像分类机器学习模型(改编自 MobileNet)用于预测。图像需要经过预处理才能通过模型​​。我使用包 resize-optimize-images get-image-data 来调整图像大小并将其更改为适合我的模型的格式。

const app = express();
const multer = require('multer');
const tf = require('@tensorflow/tfjs-node');
const image = require('get-image-data');
const resizeOptimizeImages = require('resize-optimize-images');

let model;
(async function () {
    model = await tf.loadLayersModel("http://localhost:5000/model/model.json");
})();

app.post('/classify', upload.single('file'), (req, res) => {
    
        //call methods to resize and preprocess the image
        resize();
        var input =  preprocess();

        //have model predict
        console.log(input);
        let prediction = model.predict(input);
});

这是我的 resize 函数代码。

function resize() {
    (async () => {
        // Set the options.
        const options = {
            images: [imagePath],
            width: 224,
            height: 224,
            quality: 90
        };
        
        // Run the module.
        await resizeOptimizeImages(options);
        console.log("resized");
        
    })();
}

这是我的预处理函数代码。

function preprocess() {

    image(imagePath, async (err, imageData) => {

        // pre-process image
        const numChannels = 3;
        const numPixels = imageData.width * imageData.height;
        const values = new Int32Array(numPixels * numChannels);
        const pixels = imageData.data;

        for (let i = 0; i < numPixels; i++) {
            for (let channel = 0; channel < numChannels; ++channel) {
                values[i * numChannels + channel] = pixels[i * 4 + channel];
            }
        }
        const outShape = [imageData.height, imageData.width, numChannels];
        const input = tf.tensor3d(values, outShape, 'float32');
        console.log(input);
        return input;

    });

当我运行程序时,我在调用 predict 的行收到错误“TypeError: Cannot read property 'length' of undefined”。 resize 和 preprocess 函数没有完全执行,导致要预测的输入未定义。我认为通过 resizeImageOptimizer() 放置 await,程序将等待该过程完成后再继续。然而,它似乎在最后才这样做,即使它是首先被调用的。 对此问题的任何帮助将不胜感激。

【问题讨论】:

  • 包含model = await tf.loadLayersModel(...) 的 IIFE 没有异步运行,您也没有等待它。所以它不会等待它。
  • 将异步函数放入 IIFE 不会让包含的代码等待它。

标签: javascript node.js asynchronous async-await


【解决方案1】:

好的,所以尝试像这样使用异步等待

const resize = async () => {
    const options = {
        images: [imagePath],
        width: 224,
        height: 224,
        quality: 90
    };
    
    // Run the module.
    await resizeOptimizeImages(options);
    console.log("resized");
 }

这里你也必须传递异步函数:

app.post('/classify', upload.single('file'), async (req, res) => {

    //call methods to resize and preprocess the image
    await resize();
    var input = await preprocess();

    //have model predict
    console.log(input);
    let prediction = model.predict(input)
})

请记住,async/await 仅适用于 Promise,因此您的函数(如 preprocess())也必须返回 Promise:

const preprocess = () => {
    return new Promise((resolve) => {
    image(imagePath, (err, imageData) => {

    // pre-process image
    const numChannels = 3;
    const numPixels = imageData.width * imageData.height;
    const values = new Int32Array(numPixels * numChannels);
    const pixels = imageData.data;

    for (let i = 0; i < numPixels; i++) {
        for (let channel = 0; channel < numChannels; ++channel) {
            values[i * numChannels + channel] = pixels[i * 4 + channel];
        }
    }
    const outShape = [imageData.height, imageData.width, numChannels];
    const input = tf.tensor3d(values, outShape, 'float32');
    console.log(input);
    resolve(input);

});
})
}

【讨论】:

    【解决方案2】:

    您不必放入箭头函数,只需将主函数 async 制作成 let 中的 option 对象,因为 const 用于常量值,但您提供的是动态 @987654325 @

    async function resize() {
        // Set the options.
        let options = {
          images: [imagePath],
          width: 224,
          height: 224,
          quality: 90
        };
            
        // Run the module.
        await resizeOptimizeImages(options);
        console.log("resized");
    
    }
    

    此外,您也可以将async await 放入路由中,但这是可选的:

    app.post('/classify', upload.single('file'), async (req, res) => {
        
            //call methods to resize and preprocess the image
            let resize = await resize();
            var input =  preprocess();
    
            //have model predict
            console.log(input);
            let prediction = model.predict(input);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2021-10-10
      • 2020-05-17
      • 2021-11-26
      • 2018-05-27
      • 2019-04-26
      相关资源
      最近更新 更多