【发布时间】:2018-06-03 17:11:06
【问题描述】:
我使用 Promise 来避免回调创建的嵌套结构。
但是在这段代码中我仍然有一些嵌套。是我做错了什么还是在这种情况下这是不可避免的?
在这种情况下,我想检查配置文件是否存在,如果不存在,我想创建它。
DB.getProfile(id_google).then((resGet) => {
if(!resGet[0]){
console.log('PROFILE - NOT FOUND - MUST CREATE');
DB.createProfile(id_google, email, name, pic_url).then((resCreate)=>{
console.log('PROFILE CREATED');
}).catch((error) => {
console.log('ERROR - createProfile() Failed: ', error);
});
} else {
console.log('PROFILE FOUND LOCALLY');
console.log(resGet[0]);
return done(null, resGet[0])
}
}).catch((error) => {
console.log('ERROR - getOrCreateProfile() Failed: ', error);
});
};
【问题讨论】:
-
您可以在应用程序中使用 async/await 代替 Promise 吗?
-
是的,nesting is pretty much unavoidable 用于条件语句。
-
你真的应该从你的所有函数中
return(做出承诺)而不是调用done回调。这样,您就不会忘记调用它(在创建配置文件时)。 -
@boysimpledimple async/await 不能“代替”promise。它与 with 承诺一起使用,而不是
then回调。 -
如果你这么认为,那么我建议你阅读this。它解释了为什么使用回调/承诺以及如何使用它们。如果
resGet[0]是假的并且 getProfile 被拒绝,您的函数将在 undefined 中解析。
标签: javascript express promise passport.js