包括.js文件并尝试使用生成器

时间:2015-09-22 13:04:47

标签: javascript node.js koa

我通常知道生成器/承诺在单个生成器函数中如何工作。我在另一个生成器函数内部调用生成器函数时遇到困难。

关于实际执行此操作的文章很少。该脚本似乎忽略等待用户从数据库返回并继续运行该脚本。我怎么能让它等到它完成?

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
        }
    });

1 个答案:

答案 0 :(得分:1)

DERP。 co(function* (){...})直接运行。我需要使用文档中陈述的wrap函数。

this.postSignIn = co.wrap(function* (email, password) { // user sign in