Home > other >  Order of Execution in Node.js function
Order of Execution in Node.js function

Time:10-31

getPred.js `

const {spawn} = require('child_process');
const path = require('path');
const getPred = () => {
    return new Promise((resolve, reject) => {
        var myjson = {}
        const pythonProcess =  spawn('python3', [
            "-u", 
            path.join( __dirname ,'..', '..', 'scripts', 'run.py'),
            'file'
            ]);

        pythonProcess.stdout.on('data', (data) => {
            mystr = data.toString();
            myjson = JSON.parse(mystr);
            console.log(myjson.predict);
        });
        
        pythonProcess.stderr.on('data', (data) => {
            console.log("fails")
            console.log(`error:${data}`);
            
        });
        pythonProcess.on('close', () => {
            console.log("Closed");
        });
        resolve(myjson);
    
    });
}
module.exports = {getPred};

`

main.js `

router.post('/predict',  async function (req, res, next) {
  const myjson = await getPred.getPred();
  console.log(myjson);
  console.log("Final", myjson.predict);
  res.render('print.ejs', {
    prods: myjson.predict,
    pageTitle: 'MegNav',
    path: '/',
    hasProducts: 1,
    activeShop: true,
    productCSS: true,
    onPredict: 1 
  });
});

`

Output:

Final undefined 1 Closed

In the above code, getPred() function does some python scripts and returns the predicted value. In main.js the console.log(myjson) is executing before the pythonProcess closes its connection. which endup myjson containing "Undefined".

Removing all the async, await, Promises also doest give a correct result.

Help me, so as that myjson gets the value first and so can render () the expected value

CodePudding user response:

You are calling resolve(myjson) immediately without waiting for the process to complete. Calling resolve synchronously makes the whole use of a Promise object useless. You should move that line inside the on('close', ...) or on('data', ...) handler:

        pythonProcess.on('close', () => {
            console.log("Closed");
            resolve(myjson);
        });
  • Related