简体   繁体   English

JavaScript 不等到 python 执行完成

[英]JavaScript is not waiting till the python execution is completed

I have installed python shell npm and using it to call the python script from node.js. I have installed python shell npm and using it to call the python script from node.js. At the end of the python script execution a json file will be written to the local system.在 python 脚本执行结束时,json 文件将被写入本地系统。

The thing is my javascript is not waiting for the python execution to be completed and trying to read the file that is not yet written.问题是我的 javascript 没有等待 python 执行完成并尝试读取尚未写入的文件。 So i am not getting the expected result or getting error.所以我没有得到预期的结果或出错。 Any help would be very much appreciated.任何帮助将不胜感激。 Thanks!谢谢!

Here is my code:这是我的代码:

import * as filePaths from './filePaths';
import * as scriptParameters from './pythonScriptParameters';
import * as constantmessages from './constantMessages';
import * as logger from '../Utilities/logger';
import fs from 'fs';
​
const { PythonShell } = require('python-shell');
​
export async function runManufacturingTest(){
​

PythonShell.run(scriptParameters.scriptFileName, scriptParameters.options, function(err, results) {
    if (err) {
          logger.error(err, '[ config - runManufacturingTest() ]');
      }
      const provisioningresultjson = fs.readFileSync(filePaths.provisioningresults);
      const parsedResult = JSON.parse(provisioningresultjson);
      \\ Rest of the code
​​​}
}

you should Convert callbacks to promise.您应该将回调转换为 promise。 So you can await the js thread till promise is resolved/rejected.所以你可以等待 js 线程,直到 promise 被解决/拒绝。

You can give a try to this.你可以试试这个。

 export async function runManufacturingTest() { const { success, err = '', results } = await new Promise((resolve, reject) => { PythonShell.run(scriptParameters.scriptFileName, scriptParameters.options, function( err, results ) { if (err) { logger.error(err, '[ config - runManufacturingTest() ]'); reject({ success: false, err }); } resolve({ success: true, results }); }); if (success) { const provisioningresultjson = fs.readFileSync(filePaths.provisioningresults); const parsedResult = JSON.parse(provisioningresultjson); // rest of your Code } }); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM