2017-06-16 91 views
1

我在Sails.js应用程序上运行此代码,结果是一个空的JSON。我已经阅读了几篇关于范围和上下文的文章,并且一直没能找到我做得不好的事情。Node.js/Sails.js应用程序的范围和/或上下文

var evoluciones 
    HC.find({ id: req.param('id') }).then(records => { 
     evoluciones = records;    
    }) 
    return res.json(evoluciones) 

在此先感谢。

+0

问题不在于范围...'evoluciones'是范围遍及你所列出的代码。查询可能没有返回结果。 – Kryten

+0

如果我把'res.json(evoluciones)'放在里面,那么()会返回数据。 –

+0

* Facepalm *我不敢相信,当我评论时,我没有注意到承诺。问题是你的数据库查询是**异步的** - 由'HC.find()'返回的promise在你返回数据之前不会解析。你的评论完全是正确的做法......在'then'块中调用'res.json()'。 – Kryten

回答

0

@mechuda,你可以试试这个

HC.find({ id: req.param('id') }) 
    .then(evoluciones=> { 
     // to do something 
     return [evoluciones] ; 
    }) 
    .spread((evoluciones) => { 
      return res.json(evoluciones) 
    }) 
    .fail(error => { 
      sails.log.error(error); 
      return res.negotiate(error); 
    });