2017-05-25 140 views
1

我使用Koa2框架与Nodejs 7和本地异步/等待功能。我试图在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模块获取的物品,但兴亚给了我错误

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

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

回答

3

await被用于等待的承诺得到解决,所以你可以重写你的代码到这一点:

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

此代码不会等待太物品:( – mikatakana

+0

您使用的搜索器包是哪个?这不是[这个](https://www.npmjs.com/package/searcher)。 – robertklep

+0

不,这是本地模块 – mikatakana

0

此代码是现在的工作对我来说:

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