2017-06-16 35 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); 
    }); 
相關問題