未定义NodeJS变量

时间:2018-09-17 12:53:43

标签: javascript node.js handlebars.js

我似乎找不到问题,为什么这不起作用。当我转到localhost:3000时,出现此错误ReferenceError: pixwords is not defined

app.get('/', (req, res) => {
Word.find().then((pixwords) => {
    if(!pixwords) {
     return res.send('No text available');
    }
});
res.render('index.hbs', {pixwords});
});

这是index.hbs:

{{#each pixwords}}
    {{this.text}}
{{/each}}

1 个答案:

答案 0 :(得分:2)

pixwords仅在Word.find().then()的回调函数中定义,您只能在其中使用它:

app.get('/', (req, res) => {
  Word.find().then((pixwords) => { // <-- this declares pixwords
    if (!pixwords) {
      return res.send('No text available');
    }
    res.render('index.hbs', { // <-- move the call in the .then
      pixwords
    });
  });
  // anything here is executed before Word.find has finished running
});