【问题标题】:Promise, update parent scope variable承诺,更新父范围变量
【发布时间】: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


    【解决方案1】:

    例如使用 async/await :

    createPromisified(data) {
      return new Promise((resolve, reject) => {
        post.create(data, (err, ret) => {
          if (err) return reject(err);
    
          return resolve(ret);
        });
      });
    }
    
    router.put('/test', async(ctx, next) => {
      await createPromisified(something);
    
      ctx.body = newPost;
     
      ctx.status = 200;
    })

    使用代表您的案例的通用代码示例:

    function postCreate(data, callback) {
      setTimeout(() => callback(false, 'ret'), 300);
    }
    
    function createPromisified(data) {
      return new Promise((resolve, reject) => {
        postCreate(data, (err, ret) => {
          if (err) return reject(err);
    
          return resolve(ret);
        });
      });
    }
    
    async function routerPut(ctx, next) {
      await createPromisified('something');
    
      console.log(ctx.body);
    
      ctx.body = 'newData';
    
      console.log(ctx.body);
    
      ctx.status = 200;
    }
    
    
    routerPut({
        body: 'hey',
      },
    
      () => {
        console.log('next');
      },
    );

    【讨论】:

    • 嗨,这很好,谢谢,但你能给我解释一下吗? post.create 已经返回一个 Promise。所以我测试了你的代码,但删除了包装post.createreturn new Promise,我直接返回了post.create产生的Promise的结果。但这不起作用。为什么?
    • 好的,我明白为什么了!没关系
    猜你喜欢
    • 2015-03-20
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2016-12-25
    相关资源
    最近更新 更多