[英]Is it good to use Promise this way?
我試圖理解和掌握諾言,但遇到一個問題,我不確定這是否是正確的做事方法。
我正在使用nodejs,並且具有以下內容:一個數據庫和一個模塊,在其中執行數據庫操作。 在某一時刻,我試圖在數據庫中創建一個新用戶,並在創建該用戶后在該表中為該用戶創建具有其他詳細信息的另一個條目。
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
},
function(username, password, done) {
// Before creating the user access Sequlize beforeCreate method so we can encrypt the password
User.beforeCreate(function(req) {
console.log('Encryptying password for user ',req.username)
return encryptPass(req.password)
.then(success => {
req.password = success;
})
.catch(err => {
if (err) console.error(err);
});
});
User.create({
username: username,
password: password
}).then(function(createdUser) {
console.log(createdUser);
UserDetails.create({
id:createdUser.dataValues.id
}).then((data)=>{
console.log(data);
return done(null,createdUser);
}).catch((error)=>{
console.log(error)
return done(error)
})
})
.catch(function(error) {
console.error(error)
return done(`${error.message}.`);
});
}
));
當我有這樣的事情時,這是使用諾言的正確方法嗎?
如果您需要更多信息,請告訴我,我將盡一切努力使一切變得更加清晰。
最好的問候,維克多
您可以稍微簡化一下,因為您可以刪除內部的catch
塊,只需要返回內部的Promise
User.create({
username: username,
password: password
}).then(function (createdUser) {
console.log(createdUser);
return UserDetails.create({
id: createdUser.dataValues.id
}).then((data) => {
console.log(data);
return done(null, createdUser);
})
}).catch(function (error) {
console.error(error);
return done(`${error.message}.`);
});
休息看起來還可以
謝謝大家,基於我的評論,我得到了以下代碼。 盡管我盡力避免出現回調地獄問題,但看起來還是有點像,但是由於兩個諾言都需要被調用,因此我認為這是一個很好的解決方案,而不是將其嵌套太多:
// Local sign-up strategy
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
},
function(username, password, done) {
// Before creating the user access Sequlize beforeCreate method so we can encrypt the password
User.beforeCreate(function(req) {
console.log('Encryptying password for user ',req.username)
return encryptPass(req.password)
.then(success => {
req.password = success;
})
.catch(err => {
if (err) console.error(err);
});
});
User.create({
username: username,
password: password
}).then(function(createdUser) {
console.log(createdUser);
return createdUser;
}).then((userData) =>{
UserDetails.create({
id:userData.dataValues.id
}).then((userDetails)=>{
return done(null,userData)
})
}).catch(function(error) {
console.error(error)
return done(`${error.message}.`);
});
}
));
謝謝你,維克多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.