[英]Using async/await with done()/next() middleware functions
I'm starting to use async/await. 我开始使用async / await。 Generally, what is a pattern to use await with middleware done/next functions? 通常,使用等待中间件完成/下一个功能的模式是什么?
For example, how could I replace .then() in the code below with await? 例如,我怎么能用await替换下面代码中的.then()? localAuthenticate
is done/next middleware. localAuthenticate
完成/下一个中间件。 Do I need to make a separate async
function to use await
inside it? 我是否需要创建一个单独的async
函数才能在其中使用await
?
I'd like something like this (even better w/o the try/catch): 我喜欢这样的东西(甚至更好的没有尝试/捕获):
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); }
}
Original code from Passport.js authentication middleware: 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
can only be called within an async
function - see the MDN documentation await
只能在async
函数中调用 - 请参阅MDN文档
async function localAuthenticate(User, email, password, hostname, done)
. 您的功能需要是async function localAuthenticate(User, email, password, hostname, done)
。 try/catch
is the way to catch exceptions when using await
, instead of the .then/.catch
you are used to when dealing with Promises directly. try/catch
是在使用await
时捕获异常的方法,而不是直接处理Promises时习惯的.then/.catch
。 Your function would approximate, when using async/await
: 使用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)
}
}
Further reading: 进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.