gpt4 book ai didi

javascript - nodejs 使用回调和事件

转载 作者:搜寻专家 更新时间:2023-11-01 00:10:32 25 4
gpt4 key购买 nike

我是 nodejs 编程的新手。所以请耐心等待我。

我有两个 nodejs 模块。一个传递将消息传递给另一个 nodejs 模块。第二个处理它并将结果传回到第一个模块。

方法一

第一个模块

:
secondModule.callFunction(message, function(data){
//deal with the return message from the second module

})
:

第二个模块

:
function callfunction(message, callback){

//asynchornous functions for processing
callback(data);
}
:

方法二

同样的事情,但在第二个模块中使用事件发射器完成

第一个模块

:
secondModule.callFunction(message){

})
secondModule.on('done_event', function(data){
//deal with the reply
});
:

第二个模块(使用事件发射器)

 :

function callFunction(message){

//asynchornous functions for processing
self.emit('done_event', data);
}
:

他们都正确吗?这些东西有什么区别(都是异步的)还是我做了什么蠢事。

提前致谢

最佳答案

普通回调和 EventEmitter 之间的区别事件(这是 Node 对 publisher-subscriber pattern 的实现)

  • 您可以将多个监听器附加到同一个事件。回调是一对一的通知,事件是一对多。
  • 您不能从事件中返回值。事件是一种单向消息。
  • 回调通常遵循 (error, data1, data2, data3, ...) 签名,因为单个回调负责正常和错误数据流(异步库通常期望这种行为)
  • 另一方面,基于 EventEmitter 的 api 倾向于将错误消息和非错误消息分开
  • “error”事件在事件发射器中是特殊的:如果没有监听器,EventEmitter 会抛出异常。使用回调,您有责任检查第一个错误参数。

在您的示例中,这两种方法均有效。

关于javascript - nodejs 使用回调和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16433678/

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