JavaScript不会等待python执行完成

问题描述 投票:0回答:1

我已经安装了python shell npm,并使用它从node.js调用python脚本。在python脚本执行结束时,会将json文件写入本地系统。

事情是我的javascript没有等待python执行完成并试图读取尚未写入的文件。所以我没有得到预期的结果或得到错误。任何帮助将不胜感激。谢谢!

这是我的代码:

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
​​​}
}

javascript node.js callback async-await
1个回答
0
投票

您应该将回调转换为Promise。因此,您可以等待js线程,直到承诺被解决/拒绝为止。

您可以尝试一下。

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
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.