gpt4 book ai didi

javascript - 包含一个 .js 文件并尝试使用生成器

转载 作者:行者123 更新时间:2023-11-30 00:22:15 24 4
gpt4 key购买 nike

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

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

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

应用程序.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
}
});

最佳答案

德普。 co(function* (){...}) 直接运行。我需要使用文档中说明的 wrap 函数。

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

关于javascript - 包含一个 .js 文件并尝试使用生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32717678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com