I'm confused on how this chaining for promises work, I'm still fairly new to promises and js in general so excuse me
line three, return user.findOne({email}).then((user) => {
, i'm just confused about how returning this promise does anything since it returns a other promise inside the .then()
UserSchema.statics.findByCredentials = function(email, password){
user = this;
return user.findOne({email}).then((user) => {
if (!user){
return Promise.reject();
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
if (res){
resolve(user);
}else{
reject()
}
});
});
});
}
the findByCredentials model method being used in an express app
app.post("/users/login", (req, res) => {
var body = _.pick(req.body, ["email", "password"]);
User.findByCredentials(body.email, body.password).then((user) => {
res.send(body)
}).catch((e) => {
res.send("!");
})
A simpler example I just created, this part
return plus(1).then((res) => {
return new Promise((resolve, reject) => { is the problem i'm having trouble understanding
function plus(a) {
return new Promise((resolve, reject) => {
resolve(a + 1);
});
}
function test() {
return plus(1).then((res) => {
console.log(res);
return new Promise((resolve, reject) => {
resolve("Test");
});
});
}
test().then((res) => {
console.log(res);
});