【问题标题】:How to use async/await with promise response?如何使用 async/await 和 promise 响应?
【发布时间】:2017-10-26 05:41:44
【问题描述】:

我正在使用 Koa2 框架和 Nodejs 7 和本机 async/await 函数。我正在尝试在 promise 解决后渲染模板(koa-art-template 模块)以获得结果。

const app = new koa()
const searcher = require('./src/searcher')

app.use(async (ctx) => {
  const params = ctx.request.query

  if (ctx.request.path === '/') {
    searcher.find(params).then((items) => {
      await ctx.render('main', { items }) 
    })
  }
})

我想等待通过searcher 模块获取项目,但是 Koa 给了我错误

  await ctx.render('main', { items })
        ^^^
SyntaxError: Unexpected identifier

如果我为searcher.find(params).then(...) 设置等待,应用程序将工作但不会等待项目。

【问题讨论】:

    标签: node.js async-await koa koa2


    【解决方案1】:

    await 用于等待 promise 被解析,因此您可以将代码重写为:

    app.use(async (ctx) => {
      const params = ctx.request.query
    
      if (ctx.request.path === '/') {
        let items = await searcher.find(params); // no `.then` here!
        await ctx.render('main', { items });
      }
    })
    

    如果searcher.find() 没有返回真正的承诺,你可以试试这个:

    app.use(async (ctx) => {
      const params = ctx.request.query
    
      if (ctx.request.path === '/') {
        searcher.find(params).then(async items => {
          await ctx.render('main', { items }) 
        })
       }
    })
    

    【讨论】:

    • searcher 使用的是哪个包?不是this one
    • 不,这是本地模块
    • 可以分享一下吗?如果它返回一个承诺,听起来它可能会过早地解决这个承诺。
    • 你说得对,问题出在我对搜索器模块的find 方法的实现中。感谢回复!
    【解决方案2】:

    这段代码现在对我有用:

    const app = new koa()
    const searcher = require('./src/searcher')
    
    app.use(async (ctx) => {
      const params = ctx.request.query
    
      if (ctx.request.path === '/') {
        searcher.find(params).then((items) => {
          await ctx.render('main', { items }) 
        })
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      相关资源
      最近更新 更多