【发布时间】:2015-09-22 13:04:47
【问题描述】:
我通常知道在单个生成器函数中生成器/承诺是如何工作的。我在调用另一个生成器函数中的生成器函数时遇到了困难。
关于实际执行此操作的文章很少。该脚本似乎忽略了等待用户从数据库返回并继续运行该脚本。我怎样才能让它等待它完成?
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
}
});
【问题讨论】:
标签: javascript node.js koa