gpt4 book ai didi

javascript - 处理 EventEmitter 和循环需求的更好方法是什么?

转载 作者:行者123 更新时间:2023-11-30 15:02:25 26 4
gpt4 key购买 nike

我有这样的用户服务:

'use strict';

let events = require('services/events');

module.exports = {
create: function (data) {
doCreate(data).then(user => {
events.emit('user.create');
});
},

addBonus: function (transaction) {
doSomething;
}
}

我有 events 模块:

'use strict';

let EventEmitter = require('events').EventEmitter;
let pubsub = new EventEmitter();
let userService = require('services/user');

pubsub.on('user.create', function(user) {
console.log('EVENT: user.create');
doSomething();
}

pubsub.on('payment.success', function(transaction) {
userService.addBonus(transaction); // check if it was first transaction then add bonus to user
}

module.exports = pubsub;

在这种情况下,代码有循环要求,并且代码不起作用。

我认为当 events 模块使用在该模块中发出事件的服务时很常见。设计这种情况的更好方法是什么?我有下一个想法:

  • 创建一些按事件类型分类的事件模块
  • user服务中使用构造函数

最佳答案

也许将代码分解成多个文件:

// services/user/create
let events = require('services/events');
module.exports = {
create: function (data) {
doCreate(data).then(user => {
events.emit('user.create');
});
},
}

// services/user/addBonus
module.exports = {
addBonus: function (transaction) {
doSomething;
}
}

// services/events
let EventEmitter = require('events').EventEmitter;
let pubsub = new EventEmitter();
let userService = require('services/user/addBonus');

pubsub.on('user.create', function(user) {
console.log('EVENT: user.create');
doSomething();
}

pubsub.on('payment.success', function(transaction) {
userService.addBonus(transaction); // check if it was first transaction then add bonus to user
}

关于javascript - 处理 EventEmitter 和循环需求的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308401/

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