2017-05-25 79 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 }) 
    }) 
    } 
})