试图在我的nodejs express应用程序中使用Q promise库来清理我的回调面条代码,但我在翻译它的某些部分时遇到了麻烦。在向函数传递多个参数和处理作用域时遇到麻烦。
这里是一个简化的"同步"版本来展示我的逻辑:
function updateFacebook(req, res) {
var user = getUserFromDB(userid);
var profile = getUserProfileFromAPI(accessToken);
var success = updateUserDB(user, profile);
res.json({ result: success });
}
我将回调函数转换为返回承诺
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);
超级困惑。任何指导都将不胜感激。
看起来您的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));