Reputation: 40484
I normally know how generators/promises work when in a single generator function. I am having difficulty invoking a generator function inside of another generator function.
There is very little written on actually doing this. The script seems to ignore waiting for the user to be returned from the db and continues to run the script. How may I make it wait for it to finish?
auth.js
"use strict";
var config = require('./config');
var co = require('co'); // needed for generators
var monk = require('monk');
var wrap = require('co-monk');
var db = monk(config.mongodb.url, config.mongodb.monk); // exists in app.js also
var users = wrap(db.get('users')); // export? there is another instance in app.js
var user = null;
this.postSignIn = co(function* (email, password) { // user sign in
console.log('finding email ' + email);
user =
yield users.findOne({
'local.email': email
});
if (user === null) { // local profile with email does not exists
console.log('email does not exist');
return false; // incorrect credentials redirect
} else if (user.local.password !== password) { // local profile with email exists, incorrect password
console.log('incorrect password');
return false; // incorrect credentials redirect
} else { // local profile with email exists, correct password
console.log('login successful');
return user;
}
});
app.js
"use strict";
var auth = require('./auth.js');
// ... more code
var authRouter = new router(); // for authentication requests (sign in)
authRouter
.post('/local', function* (next) {
var user =
yield auth.postSignIn(this.request.body.email, this.request.body.password); // returns user or false
if (user !== false) { // correct credentials // <--- it hits here before the user is retrieved from the database
// do something
} else { // incorrect credentials
// do something
}
});
Upvotes: 2
Views: 24
Reputation: 40484
Derp. co(function* (){...})
is run directly. I needed to use the wrap function stated in the documentation.
this.postSignIn = co.wrap(function* (email, password) { // user sign in
Upvotes: 1