尝试使用我的nodejs express app中的Q promise库清理我的回调意大利面条代码,但是我在翻译它的某些部分时遇到了麻烦。无法将多个参数传递给函数并处理范围。
这是一个简化的“同步”版本,用于显示我的逻辑:
function updateFacebook(req, res) {
var user = getUserFromDB(userid);
var profile = getUserProfileFromAPI(accessToken);
var success = updateUserDB(user, profile);
res.json({ result: success });
}
所以我将回调函数转换为return promises
function getUserFromDB(userid) {
var deferred = Q.defer();
// somewhere in here there's a deferred.resolve(user object);
queryMongo()...
return deferred.promise;
}
function getUserProfileFromAPI(accessToken) {
var deferred = Q.defer();
// somewhere in here there's a deferred.resolve(profile object);
request()...
return deferred.promise;
}
function updateUserDB(user, profile) {
var deferred = Q.defer();
// somewhere in here there's a deferred.resolve(updated user object);
updateMongo()...
return deferred.promise;
}
function handleResponse(res, user) {
var deferred = Q.defer();
// was thinking about putting the res.json here
// i have no way of passing in the res
// and res is out of scope...
res.json({});
return deferred.promise;
}
现在问题是将它们联系起来,我试过......
Q.when(getUserFromDB(userid), getUserProfileFromAPI(accessToken))
.spread(updateUserDB)
.done(handleResponse);
Q.all([getUserFromDB(userid), getUserProfileFromAPI(accessToken)])
.spread(updateUserDB)
.done(handleResponse);
超级困惑。任何方向都会非常感激。
答案 0 :(得分:3)
看起来您的handleResponse
期待两个参数,但updateUserDB
只能解析一个对象。你可以这样做:
function getResponseHandler(res) {
return function(user) {
// your handleResponse code here
// which now has access to res
}
}
然后将其称为:
Q.all([getUserFromDB(userid), getUserProfileFromAPI(accessToken)])
.spread(updateUserDB)
.done(getResponseHandler(res));