我有一个类似于这个的代码:
promise_function().then(()=>{
//do something
return another_promise_fucntion();
}).then(() => {
//do something
return another_promise_function1();
}).then((result) => {
//check if result is valid
if(!result)
//break chain (how to stop calling the next .then functions ?)
else
return another_promise_function2();
}).then(()=>{
//do something
return another_promise_function3();
}).catch((err)=>{
//handle error
});
Run Code Online (Sandbox Code Playgroud)
如果返回的结果无效,我想停止调用下一个.then()函数.
我使用"throw new Error()",它工作得很好,但我不确定它是否是推荐的方式.
我想为passport-jwt 创建一个自定义中间件来处理身份验证。
这是我为创建自己的中间件所做的工作:
var models = require('../models');
var passport = require("passport");
var passportJWT = require("passport-jwt");
var config = require("../config/config.json");
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
var params = {
secretOrKey: config.jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeader()
};
/**
* jwt authentication strategy
*/
var strategy = new Strategy(params, function(payload, done) {
models.User.findById(payload.id)
.then((user)=>{
if (user) {
return done(null, {
id: user.id,
username : user.username
});
} else {
return done(new Error("User not found"), false);
}
}).catch((err)=>{
return done(err, false);
});
}); …Run Code Online (Sandbox Code Playgroud)