2017-08-22 47 views
0

我是Node JS的新手。我的節點JS REST API航線代碼:如何在節點js中返回對REST API的響應

'use strict'; 
module.exports = function(app) { 
    var sequel = require('../controllers/sampleController'); 
    app.get('/task?:email', function(req, res){ 
     res.send(sequel.listByEmail(req.query.email)); 
    }); 
}; 

而且我listByEmail功能是:

'use strict'; 
var apiKey = '1xxxxxxxxL'; 
exports.listByEmail = function(emailid) { 
    console.log(emailid); 
    if(emailid != null && emailid != undefined) { 
     var xyz = require("xyz-api")(apiKey); 
     xyz.person.findByEmail(emailid, function(err, data) { 
      if(data.status == 200){ 
       return data; // data is in json format 
      } 
     }); 
    } 
}; 

我從listbyemail函數返回的數據是這樣的。數據在那裏,如果我嘗試在控制檯中顯示數據。但在返回數據時,它不會返回。它總是返回undefined。我無法從路由中的listByEmail函數捕獲結果數據,也無法將其作爲響應發送。請幫幫我!!!

回答

2

在您的ListByEmail函數中,您正在調用異步方法findByEmail

當你到達return data;行時,你的listByEmail函數已經返回,所以你沒有返回任何東西給調用者。

你需要異步處理它,例如:

'use strict'; 
var apiKey = '1xxxxxxxxL'; 
exports.listByEmail = function(emailid) { 
    return new Promise(function(resolve, reject) { 
     console.log(emailid); 
     if(emailid != null && emailid != undefined) { 
      var xyz = require("xyz-api")(apiKey); 
      xyz.person.findByEmail(emailid, function(err, data) { 
       if(data.status == 200){ 
        resolve(data); // data is in json format 
       } 
      }); 
     } else { 
      reject("Invalid input"); 
     } 
    }; 

然後:

'use strict'; 
module.exports = function(app) { 
    var sequel = require('../controllers/sampleController'); 
    app.get('/task?:email', function(req, res){ 
     sequel.listByEmail(req.query.email).then(function(data) { 
      res.send(data); 
     }); 
    }); 
}; 

這是使用Promise來處理節點異步調用的一個非常基本的例子。你應該研究一下它是如何工作的。您可以通過閱讀這個開始,例如:一旦你瞭解如何應對回調https://www.promisejs.org/

+0

感謝您的幫助,肯定會研究有關承諾。 –

0

UPD,你最好把目光投向Promisesasync/await,並async.js

你的功能#findByEmail是異步的,所以有可能你的路線應該像

'use strict'; 
module.exports = function(app) { 
    var sequel = require('../controllers/sampleController'); 
    app.get('/task?:email', function(req, res){ 
     sequel.listByEmail(req.query.email, function(err, list){ 
      if(err){ 
      console.error(err); 
      //handle error 
      } 
      res.send(list); 
     }) 
    }); 
}; 

和你#listByEmail功能應該像

'use strict'; 
var apiKey = '1xxxxxxxxL'; 
exports.listByEmail = function(emailid, callback) { 
    console.log(emailid); 
    if(emailid != null && emailid != undefined) { 
     var xyz = require("xyz-api")(apiKey); 
     xyz.person.findByEmail(emailid, function(err, data) { 
      if(err){ 
       callback(err); 
      } else if(data.status == 200){ 
       callback(null, data); 
      } 
     }); 
    } 
}; 
+0

這也是有效的。謝謝魯道夫 –

相關問題