【发布时间】:2019-02-10 01:23:03
【问题描述】:
我有这个代码:
router.put('/test', (ctx, next) => {
post.create(something, (err, newPost) => {
if (err) return
ctx.body = newPost
})
console.log(ctx.body) // => undefined
ctx.status = 200
})
问题是我在回调中为 ctx.body 变量设置的值在回调之外丢失。
而且我无法让它发挥作用。我试过bind/async await,但没有成功。
你能帮帮我吗?
编辑:@CertainPerformance,您链接的“重复”post 没有回答我的问题,因为它提出的解决方案包括直接修改函数的签名,在我的情况下产生承诺 post.create。我不能简单地这样做,因为它是 Mongoose API 的一部分。我阅读了整篇文章,但没有找到解决方案。那么我们如何处理这篇文章呢?
编辑:根据下面的答案,我找到了两个解决方案:
router.put('/test', async (ctx, next) => {
const newPost = await Post.create(something).then(post => post)
ctx.body = newPost
ctx.status = 200
})
和
router.put('/test', async (ctx, next) => {
const newPost = new Post(something)
await newPost.save()
ctx.body = newPost
ctx.status = 200
})
【问题讨论】:
标签: javascript mongoose ecmascript-6 promise es6-promise