node.js - Passport.authenticate() 使用 Promise 而不是自定义回调

标签 node.js authentication promise passport.js

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/

相关文章:

node.js - Google Cloud App Engine 上的 Nodejs 应用无法启动

node.js - 在 Swig 模板中使用 include 时连接变量和文件

javascript - 在端口 80 以外的端口上运行 node.js

wcf - 如何保护 .NET WCF 中的 HTTP JSON Web 服务

javascript - 未捕获( promise )TypeError : undefined is not a function (Vue. js,Electron)

node.js - 当使用来自不同本地主机端口的 GET api 时,本地主机上的 Angular 收到 404 - CORS 问题?

internet-explorer - IE 保护模式 + SSL 登录 = 非 SSL 页面无 cookie

java - 验证方法应该返回 null 还是 AuthentificationException?

javascript - 带有 node.js promise 的 RPC

javascript - AngularJS:超时 promise 调用