簡體   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. 在 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
​​​}
}

您應該將回調轉換為 promise。 所以你可以等待 js 線程,直到 promise 被解決/拒絕。

你可以試試這個。

 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