这更像是一个逻辑上的概念问题,我可以减少下面的代码。根据评论,提取用户信息并将其放入props
。然后从数据库中提取相同的用户数据,以使用done
返回。
我认为代码的原作者想要确保它已保存到数据库中。但我认为这太过分了。
错误检查会告诉我们是否出现任何问题,保存后我们不需要立即提取数据。我们只能返回存储的相同数据。
这是护照验证码。
// the user was not found
// create the user, get the user, and return the user object
function createUser (done, profile) {
let props = obtainProps(profile);
DBM.createUser(props).then(() => {
DBM.getUser(props.id_google).then((res) => {
return done(null, res[0]);
}).catch( error => {
return done(error, null);
});
});
}
到此代码:
// the user was not found
// create the user then return props
function createUser (done, profile) {
let props = obtainProps(profile);
DBM.createUser(props).then(() => {
return done(null, props);
}).catch( error => {
return done(error, null);
});
}
答案 0 :(得分:0)
我认为你也可以省略检查,另外,如评论所述,使用Promise并返回它是有意义的,而不是传递一个回调并在promise then
中执行它。承诺取代了回调,你的代码正朝着另一个方向发展。您的createUser函数应该类似于
function createUser (profile) {
let props = obtainProps(profile);
return DBM.createUser(props);
}
如果您需要其他地方的结果,请使用then
// somewhere else in your code
createUser().then(e => /* e is result of DBM.createUser */)