Я обычно знаю, как генераторы/обещания работают, когда в одной функции генератора. У меня возникают трудности с вызовом функции генератора внутри другой функции генератора., включая файл .js и пытающийся использовать генераторы
На самом деле очень мало написано. Сценарий, кажется, игнорирует ожидание возврата пользователя из базы данных и продолжает запускать скрипт. Как я могу заставить его дождаться окончания?
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
}
});