ep.group(‘got_file’); // 约等价于 function (err, data) { if (err) { return ep.emit(‘error’, err); } ep.emit(‘got_file’, data); };
ep.done(‘tpl’); // 等价于 function (err, content) { if (err) { // 一旦发生异常,一律交给error事件的handler处理 return ep.emit(‘error’, err); } ep.emit(‘tpl’, content); }
看这个的约等价关系,ep.done和ep.group在用法上应该是差不多的,区别是结果顺序与emit发射的顺序相关,但是在使用的时候,ep.done成功的时候,换成ep.group会报错。
var index = that._after[group].index;
TypeError: Cannot read property ‘find_question_group’ of undefined at EventProxy.group (e:\mycode\github\zhihu\node_modules\eventproxy\lib\eventproxy.js:443:28)
在eventproxy源码中
EventProxy.prototype.group = function (eventname, callback) { var that = this; var group = eventname + ‘_group’; var index = that._after[group].index; that._after[group].index++;
that = undefined ?? 求解答~~
看你这个异常的的样子,应该是that._after是undefined吧。 我猜测你是在非after方式下使用group来替换done吧,又或者after第二个参数是0? 可以看一下你截取的group上的注释。
- @param {String} eventname Event name, should keep consistent with
after
.
Topic.getAll(function (err, topics, tags) { var ep = new eventproxy(); topics.forEach(function (topic) { Question.findQuestionByTopic(topic, ep.group(‘get_questions’)); }); ep.after(‘get_questions’, topics.length, function (list) { console.log(tags) console.log(list) return res.render(‘topic/topic’, { topics: list, tags: tags, err: req.flash(‘err’).toString() }); }); });
// group那里改成done是可以出结果的,改成group,就报题目说的错了。 // done,log了一下,顺序是乱的
[ ‘111’, ‘222’, ‘qwer’ ] // tags [ [ { _id: 55efd7a4d2e4b37c186a5680, // list tags: [ ‘111’, ‘222’, ‘333’ ] }, { _id: 55efd7add2e4b37c186a5684, tags: [ ‘111’, ‘222’ ] } ], [ { _id: 55efd7ccd2e4b37c186a5689, tags: [ ‘qwer’ ] } ], [ { _id: 55efd7a4d2e4b37c186a5680, tags: [ ‘111’, ‘222’, ‘333’ ] }, { _id: 55efd7add2e4b37c186a5684, tags: [ ‘111’, ‘222’ ] } ] ]
@yxfanxiao 代码顺序的问题?ep.after 还未初始化时,已经有ep.group被执行了? 试试这样呢?
Topic.getAll(function (err, topics, tags) {
var ep = new eventproxy();
ep.after('get_questions’, topics.length, function (list) {
console.log(tags)
console.log(list)
return res.render('topic/topic’, {
topics: list,
tags: tags,
err: req.flash(‘err’).toString()
});
});
topics.forEach(function (topic) {
Question.findQuestionByTopic(topic, ep.group(‘get_questions’));
});
});