passport.authenticate()
,如何定义 Promise 而不是使用自定义 Ballback?
此处引用了如何使用passport.authenticate()
:
http://www.passportjs.org/docs/authenticate/
在此页面中,有一个部分自定义 Ballback:
If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
自定义回调定义为:
function(err, user, info){...}
我想做的是用Promise替换这个自定义回调。
[Promise](resolve, reject)
.then(res => {
})
.catch(err => {
})
我该怎么做?谢谢。
最佳答案
您可以使用es6-promisify包裹。它非常容易使用,这是一个示例:
const {promisify} = require("es6-promisify");
// Convert the stat function
const fs = require("fs");
const stat = promisify(fs.stat);
// Now usable as a promise!
stat("example.txt").then(function (stats) {
console.log("Got stats", stats);
}).catch(function (err) {
console.error("Yikes!", err);
});
关于node.js - Passport.authenticate() 使用 Promise 而不是自定义回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328833/