首页 文章

如何使用async / await和promise响应?

提问于
浏览
1

我正在使用带有 Nodejs 7Koa2 框架和本机异步/等待函数 . 而且我正在尝试在promise解析后为结果渲染模板( koa-art-template module) .

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(...) ,应用程序将起作用,但不会等待项目 .

2 回答

  • 0

    await 用于等待promises得到解决,因此您可以将代码重写为:

    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 }) 
        })
       }
    })
    
  • 4

    这段代码现在对我有用:

    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 }) 
        })
      }
    })
    

相关问题