mikatakana
mikatakana

Reputation: 523

How to use async/await with promise response?

I'm using Koa2 framework with Nodejs 7 and native async/await functions. And I'm trying to render template (koa-art-template module) for results after promise resolves.

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

I want to wait for getting items by searcher module, but Koa gives me error

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

If i will set await for searcher.find(params).then(...), an application will work but won't wait for items.

Upvotes: 1

Views: 964

Answers (2)

mikatakana
mikatakana

Reputation: 523

This code is working for me now:

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

Upvotes: 0

robertklep
robertklep

Reputation: 203379

await is used to wait for promises to be resolved, so you can rewrite your code to this:

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

If searcher.find() doesn't return a real promise, you can try this instead:

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

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

Upvotes: 4

Related Questions