Node.js 如何将异步/等待与承诺响应一起使用?

Node.js 如何将异步/等待与承诺响应一起使用?,node.js,async-await,koa,koa2,Node.js,Async Await,Koa,Koa2,我将Koa2框架与Nodejs 7和本机异步/等待函数一起使用。我正在尝试在promise解决后为结果渲染模板koa艺术模板模块 const app = new koa() const searcher = require('./src/searcher') app.use(async (ctx) => { const params = ctx.request.query if (ctx.request.path === '/') { searcher.find(par

我将Koa2框架与Nodejs 7和本机异步/等待函数一起使用。我正在尝试在promise解决后为结果渲染模板koa艺术模板模块

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 }) 
    })
  }
})
<>我想等待搜索器获取项目,但是Koa给了我错误< /P>
  await ctx.render('main', { items })
        ^^^
SyntaxError: Unexpected identifier
如果我将为searcher.findparams.then…设置wait,则应用程序将工作,但不会等待项目。

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

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 }) 
    })
   }
})
wait用于等待承诺得到解决,因此您可以将代码重写为:

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

此代码现在适用于我:

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

此代码现在适用于我:

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模块的find方法上实现的。谢谢回复!您使用哪个软件包进行搜索?不是。不,这是本地模块。你能分享吗?如果它返回一个承诺,听起来它可能会过早地解决这个承诺。你是真的,问题是我在searcher模块的find方法上实现的。谢谢回复!