【问题标题】:Does Express.js http response returns a promise by defaultExpress.js http响应是否默认返回一个promise
【发布时间】:2020-10-31 21:48:24
【问题描述】:

例如,下面代码中的res.send(user) 是否返回了一个promise?

app.post('/users', (req, res) => {
    const user = new User(req.body)

    user.save().then(() => {
        res.send(user)
    }).catch((e) => {
        res.status(400).send(e)
    })
})

【问题讨论】:

    标签: node.js express http


    【解决方案1】:

    不,如果你想返回一个 Promise,你应该使用异步函数而不是同步函数。 Promise 多年来一直是该语言的一部分(在 ES2015 中标准化和引入),并且最近变得更加集成,在 ES2017 中使用 async 和 await。

    app.post('/users', async (req, res) => {
       try{
           const user = new User(req.body);
           await user.save();
           res.send(user);
       } catch(e){
           res.status(400).send(e);
       }
    }
    

    【讨论】:

    • 你不需要等待 req.body const user = new User( req.body)
    • 如果你使用 async-await 你就不需要打电话了。 await user.save() 和下面的一行 res.send(user)
    • @Abjullah 回调中的 async-await 不会影响 res.send 方法。如果我们要从那个函数返回一些东西,它会返回一个 Promise,但是 express 无论如何都不会将它用于 res.send。我仍然没有答案(我也假设它没有返回一个承诺,但目前无法证明它),欢迎您再试一次
    猜你喜欢
    • 2021-10-18
    • 2016-03-19
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多