我正在使用promises重構我的代碼。我遇到了一個問題。我有兩個API路由。第一個是api.js,第二個是account.js。我也有4個控制器(CommentController,ZoneController,ProfileController,AccountController)。REStful API承諾調用另一個承諾
CommentController,ZoneController和ProfileController可共享相同的API路線(api.js)。
account.js使用的AccountController。但是AccountController的方法使用ProfileController的方法。
我最後不得不無極調用另一個承諾,但我無法正常返回數據。它正在離開服務器掛起。當一個Promise調用另一個Promise時,我怎樣才能返回數據? 基本上account.js調用了AccountController.js,它有一個調用ProfileController.js的方法,但AccountController和ProfileController都被重構爲Promise。我沒有收回數據。請幫忙。
AccountController.js
var ProfileController = require('./ProfileController');
module.exports = {
currentUser: function(req) {
return new Promise(function(resolve, reject) {
if (req.session == null) {
reject({message: 'User not logged in'});
return;
}
if (req.session.user == null) {
reject({message: 'User not logged in'});
return;
}
ProfileController.findById(req.session.user, function(err, result) {
if (err) {
reject({message: 'fail'});
return;
}
resolve(result);
return;
});
});
}
ProfileController.js
findById: function(id) {
return new Promise(function(resolve, reject){
Profile.findById(id, function(err, profile){
if(err){
reject(err);
return;
}
resolve(profile);
return;
});
})
},
account.js
router.get('/:action', function(req, res, next) {
var action = req.params.action;
if (action == 'logout') {
req.session.reset();
res.json({
confirmation: 'success',
message: 'Bye!'
});
return;
}
if (action == 'login') {
res.json({
confirmation: 'success',
action: action
});
return;
}
if (action == 'currentuser') {
AccountController.currentUser(req)
.then(function(result){
res.json({
confirmation: 'success',
user: result
});
return;
})
.catch(function(err){
res.json({
confirmation: 'fail',
message: err.message
});
return;
});
}
});
看來你忘了修改'currentUser'功能'AccountController'使用在'ProfileController'您的重構'findById'功能:你正在傳遞一個回調函數,雖然'findById'只需要一個'id'參數 –
也請包含一些測試用例,因爲我們不知道你會期待什麼樣的輸出 –
謝謝你看看我的問題。 Kermit解決方案已解決。 –