Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of Execution in Node.js function

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
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
        });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading