【问题标题】:Where should i put async and await?我应该把异步和等待放在哪里?
【发布时间】:2019-12-08 00:27:00
【问题描述】:

我应该把异步和等待放在哪里? 结果是 工作2 工作1

app.post('/upload', (req, res) => {
    const txtupload = multer().any()
    let validate = true
    txtupload(req,res, (err)=>{
        console.log('work1')
        validate = false
    })

    if(validate){
        console.log('work2')
        //code
    }
});

【问题讨论】:

  • 在这种情况下,您可能根本不使用async/await,而是将所有代码放入内部回调中。
  • 在上传之前我想设置一些条件来阻止上传。 txt上传后我会再次上传文件

标签: javascript node.js asynchronous async-await


【解决方案1】:

来自multer 的上传函数不返回承诺,因此async/await 不适用。相反,请在回调中发出您的响应。

您真正的问题似乎是:如何使用multer 处理文件上传?为此,我们转到multer documentation。使该文档适应您的代码:

app.post('/upload', (req, res) => {
    const txtupload = multer().any();
    txtupload(req,res, (err) => {
        if (err) {
            // ...it failed, send a failure response via `res`...
        } else {
            // ...it worked, send a success response via `res`...
        }
    });
    // Don't do anything here, the upload hasn't been processed yet
});

但是参考文档中的示例,还有其他使用multer的模式。

【讨论】:

    【解决方案2】:

    由于是箭头函数,所以必须放在参数之前:

    app.post('/upload', async (req, res) => { ... }
    

    【讨论】:

    • 我不知道这是否被称为“变量”,但我想知道它是否是别的东西,真的。
    • 它们被称为“参数”;整个事物被称为“参数列表”。但是OP的代码不能使用await,所以这没有多大意义。
    • 哦,是的,但他可能是因为别的原因才看的。而且,由于 multer 是一个中间件,我认为他应该在 parameters 之前使用它:app.post('/upload', multer().any(), (req, res) => { ... }
    • the documentation,这是两种使用方式之一(另一种大致是OP使用的方式)。
    • 仅供参考,这里没有使用 async 函数,因为没有使用承诺,因此没有地方放置 await。这个答案可能会误导 OP 认为他们可以使用 awaittxtupload(),除非他们先承诺,否则他们不能这样做。
    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多