[英]Using async/await with done()/next() middleware functions
我開始使用async / await。 通常,使用等待中間件完成/下一個功能的模式是什么?
例如,我怎么能用await替換下面代碼中的.then()? localAuthenticate
完成/下一個中間件。 我是否需要創建一個單獨的async
函數才能在其中使用await
?
我喜歡這樣的東西(甚至更好的沒有嘗試/捕獲):
function localAuthenticate(User, email, password, hostname, done) {
try { // where is async?
// Find user
let user = await User.findOne({ email: email.toLowerCase() }).exec()
if(!user) return done(null, false, { message: 'This email is not registered.' });
// Test password
user.authenticate(password, function(authError, authenticated) {
if(authError) return done(authError);
if(!authenticated) return done(null, false, { message: 'This password is not correct.' });
return done(null, user);
});
} catch(err) { done(err); }
}
Passport.js身份驗證中間件的原始代碼:
function localAuthenticate(User, email, password, hostname, done) {
User.findOne({
email: email.toLowerCase()
}).exec()
.then(user => {
if(!user) {
return done(null, false, {
message: 'This email is not registered.'
});
}
user.authenticate(password, function(authError, authenticated) {
if(authError) {
return done(authError);
}
if(!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
} else {
return done(null, user);
}
});
})
.catch(err => done(err));
}
await
只能在async
函數中調用 - 請參閱MDN文檔
async function localAuthenticate(User, email, password, hostname, done)
。 try/catch
是在使用await
時捕獲異常的方法,而不是直接處理Promises時習慣的.then/.catch
。 使用async/await
時,您的函數將近似為:
async function localAuthenticate(User, email, password, hostname, done) {
try {
// Find user
let user = await User.findOne({ email: email.toLowerCase() }).exec()
if (!user) {
return done(null, false, { message: 'This email is not registered.' })
}
user.authenticate(password, function (authError, authenticated) {
if (authError) {
return done(authError)
}
if (!authenticated) {
return done(null, false, { message: 'This password is not correct.' });
}
return done(null, user);
})
} catch (err) {
done(err)
}
}
進一步閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.