简体   繁体   English

这个回调函数如何工作

[英]how does this callback function work

I am new to nodejs and almost n00b of JavaScript. 我是nodejs和n00b的JavaScript的新手。 I saw the code to create a server using nodejs. 我看到了使用nodejs创建服务器的代码。 I can understand that the anonymous function is called after a request reached the server. 我可以理解,在请求到达服务器后将调用匿名函数。

var http=require("http");
http.createServer(function(request,response){
 response.writeHead(200,{"Content-Type":"text/plain"});
 response.write("hello world");
 responde.end();
}).listen(8888); 

My question is how to implement something similar like createServer function (foo() bar())..in order to understand how this method works. 我的问题是如何实现类似createServer function(foo()bar())之类的东西以了解此方法的工作原理。

In order to make it clear. 为了清楚起见。 I have done this that is not working. 我这样做是行不通的。 and how to make it work like createServer() ? 以及如何使其像createServer()一样工作?

function dummycallback(para1,para2,callback)
{
 console.log('para1 is ' + para1+' para2 is '+ para2);
 callback();
}

dummycallback(1,2,function(req,res)
{
 req.senddata("good");
});

I have seen these code everywhere in nodejs so I am desperately want to know the details...thanks again 我在nodejs中到处都看到了这些代码,所以我非常想知道细节...再次感谢

Maybe, you are asking how the anonymous function works. 也许您在问匿名函数如何工作。

var fun = function(foo){
    if (foo) foo(1, 2); ///< if function foo exists, call it.
}
fun(function(p1, p2){
    return p1 + p2;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM