【发布时间】:2019-08-17 23:57:36
【问题描述】:
我试图让我的 post 方法等到用户刚刚上传的文件上的 python 脚本完成。我相信问题是由于 app.post 不是异步的,但我不确定如何使其异步。
我已尝试对以下代码进行多次修改。
async function pythonScript(file, cb){
try{
var PythonShell = require('python-shell');
// Use python shell
var {PythonShell} = require('python-shell');
console.log("Filename = " + File1)
var options = {
mode: 'text',
args: [File1, File2, File3]
};
PythonShell.run('pythonFile.py', options, function (err, results) {
if (err) throw err;
console.log(results[results.length-1]);
result = results[results.length-1];
output = result;
console.log("output " + output);
});
return output;
catch(error){
console.log(error)
}
}
app.post('/upload', async(req, res), (req, res) => {
upload(req, res, (err) => {
if(err){
res.render('index', {
msg: err
});
} else {
if(req.file == undefined){
res.render('index', {
msg: 'Error: No File Selected!'
});
} else {
await pythonScript(file, cb).then(res.render('index', {
file: `uploads/${req.file.filename}`,
msg: 'File Uploaded! '+ output
}));
}
}
});
});
pythonScript方法需要在页面渲染之前完成,否则'output'变量将为空(输出在pythonScript方法中设置。
【问题讨论】:
-
您需要将回调声明为异步上传:
async (err) => { ...。 -
在 pythonScript 完成之前,您仍在调用 res.render。将其移到 await 下方,而不是使用
then。
标签: python node.js asynchronous async-await