【问题标题】:How to fix "SyntaxError: await is only valid in async function"如何修复“语法错误:等待仅在异步函数中有效”
【发布时间】: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


【解决方案1】:

您必须将回调声明为 async 才能在它们上使用 await。您的正确代码应该是

app.post('/upload', async (req, res) => {
  upload(req, res, async (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 
        }));
      }
    }
  });

});

【讨论】:

  • 感谢您的评论,我发现问题在于,当我的函数运行异步时,PythonShell 总是会在 ri 运行后立即吐出一些东西。如果其他人遇到此问题,请使用与我使用的代码和我使用的代码类似的代码,无论您在 PythonShell.run 参数中声明的结果是什么,请使用检查该值何时更改为不同的值(我使用了等待)这将使函数等待直到实际找到结果,而不是当 PythonShell 返回时(不是脚本完成时)
【解决方案2】:

我正确地异步调用了函数,但是 Python-Shell 在函数完成之前返回了一个值。 Python-Shell 一旦被调用就会返回一个 blob/json。因此,当我以异步方式运行它时,它等待的时间不足以让我的功能完成。

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2019-07-15
    • 2021-02-03
    • 1970-01-01
    相关资源
    最近更新 更多