我按照此处的说明操作:https://github.com/kriskowal/q#handling-errors
但我无法让我的promises返回处理程序抛出错误。它偷偷地失败了。这使得调试变得非常困难。谁能弄明白我做错了什么?
这是我的功能:
app.get('/api/recommend',function (req, res) {
var results = require('./recommend').getOriginProfiles(req.query['origin'], req.query['target']).then(
function getRecommendations(results) {
// debugger;
sasd / asdasdasdasdasdasd; // fail darn you!
require('./recommend').matchProfile(results[0]);
res.send(results);
}).fail(function (error) { //never failed
throw error;
});
logger.log('DEBUG', '/api/recommend response', results);
});
getOriginProfiles是一个返回promise的函数:
function getOriginProfiles(origin_qty, target_qty) {
var deferred = q.defer();
chooseRandomUsers(origin_qty).then(collectUserProfiles(origin_qty, target_qty, deferred), function (error) {
logger.log('ERROR', 'recommending users', error);
throw error;
});
return deferred.promise;
}
答案 0 :(得分:1)
我会这样写:
var recommend = require('./recommend');
app.get('/api/recommend',function (req, res, next) {
recommend.getOriginProfiles(req.query['origin'], req.query['target'])
.then(function getRecommendations(results) {
sasd / asdasdasdasdasdasd; // fail darn you!
recommend.matchProfile(results[0]);
res.send(results);
logger.log('DEBUG', '/api/recommend response', results);
})
.fail(function (error) {
next(error)
})
// Any function where you use a promise that isn't also returning a
// promise should have .done on the chain to prevent it from swallowing
// all exceptions.
.done();
});
和
function getOriginProfiles(origin_qty, target_qty) {
return chooseRandomUsers(origin_qty)
.then(function(users){
// Return the promise here will then wait for that promise to finish.
return collectUserProfiles(users, origin_qty, target_qty);
})
.fail(function (error) {
logger.log('ERROR', 'recommending users', error);
throw error;
});
}