如何从外部脚本的回调中返回JavaScript

0 投票
1 回答
600 浏览
提问于 2025-04-18 11:55

我把 Python Shell 和 NodeJS 配置在一起了。
我想通过调用一个回调函数来从 Python Shell 返回结果。
这个回调函数能够成功地把 Python Shell 的结果打印到控制台,但我却无法把结果返回。我觉得这是因为 PythonShell.run 这个方法不支持返回值。

// Python Invocation
exports.find = function (searchterm) {
  var PythonShell = require('python-shell');

  function callback (err, results) {
    console.log(results); //Exhibit A (logs successfully)
  }

  // PythonShell does not support return
  PythonShell.run('findAnswer.py', callback);

  //How do I return Exhibit A?
};

如果有任何建议,我会很感激。

谢谢!

1 个回答

0

你可以像下面这样修改你的函数

exports.find = function (searchterm, callback) {
  var PythonShell = require('python-shell');

  // PythonShell does not support return
  PythonShell.run('findAnswer.py', callback);
};

然后可以这样使用:

var finds = require('modulename').find;

finds('search term', function(err, results){
 //do anything with results here
});

撰写回答