前提・実現したいこと
koav2 + sequelize + koa-ejs で Web アプリを作り始めています。
koa でサーバが起動し、sequelize でモデルを作成してデータを取得でき、ejs でダミーデータを渡して表示するところまでは確認できたのですが
それらを組み合わせて、いざ取得したデータをビューに渡そうとしたところで、上手くいかず困っています。
koa や sequelize というより、Promise の使い方で引っかかっています... どうかご教授ください。
発生している問題・エラーメッセージ
$ node server.js /path/to/server.js:21 await ctx.render('index', { lands }); ^^^ SyntaxError: Unexpected identifier at createScript (vm.js:53:10) at Object.runInThisContext (vm.js:95:10) at Module._compile (module.js:543:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:423:7) at startup (bootstrap_node.js:147:9)
該当のソースコード
javascript
1const koa = require('koa'); 2const render = require('koa-ejs'); 3const path = require('path'); 4const app = new koa(); 5 6const models = require('./src/models'); 7 8render(app, { 9 root: path.join(__dirname, 'src/views'), 10 layout: 'template', 11 viewExt: 'html', 12 cache: false, 13 debug: true 14}); 15 16app.use(async function (ctx) { 17 models.land.findAll({ 18 attributes: ["id", "address", "x", "y"], 19 raw: true, 20 }).then(function (lands) { 21 await ctx.render('index', { lands }); // => ctx が Syntax Error 22 }); 23}); 24 25app.listen(3000);
試したこと
一度 models.land.findAll...
を変数として受け取ってから await ctx.render...
を実行してみたのですが、変数には Promise が返るため上手くいかず。
javascript
1app.use(async function (ctx) { 2 let lands = models.land.findAll({ 3 attributes: ["id", "address", "x", "y"], 4 raw: true, 5 }).then(function (lands) { 6 return lands; 7 }); 8 await ctx.render('index', { lands }); // => lands は Promise なので表示できずエラー 9});
Promise が実行されるまで待ってからその値を受け取れるといいのですが、どうしたらいいのでしょう。
補足情報(言語/FW/ツール等のバージョンなど)
Node v7.8 を使用しています。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/05 03:52