NodeJS – 不能实现asynchronousfunction

我在NodeJs新手。 这是我学习asynchronous函数的代码。

//--------------------- MAIN --------------- console.log("Endpoint 1\r\n"); testThread(1000000000,function (result){ console.log(">>>>"+result+"\r\n"); }); console.log("Endpoint 2\r\n"); //------------------------------------------ function testThread(data,callback) { //take a long time for(j=0;j<data;j++) { a = 122342342342424242431*3543652636364; } // callback(a); } 

运行:

 node testthread.js 

总是结果是:

 Endpoint 1 >>>>4.335387639806787e+32 Endpoint 2 

系统打印“端点1”,花费2秒,打印“>>>> 4.335387639806787e + 32”后打印“端点2”

我在这里找不到asynchronous。 它应该是:

 Endpoint 1 Endpoint 2 >>>>4.335387639806787e+32 

请解释我

asynchronous函数是调用其他asynchronous函数的函数。 在javascript / node.js中没有其他方法来实现asynchronous函数。 最初看起来像鸡和鸡蛋的问题不是吗? 如果需要调用另一个asynchronous函数来实现asynchronous,如何编写一个asynchronous函数?

答案是最低级别的asynchronous函数必须在C中实现

幸运的是,javascript / node.js在C语言中实现了一些内置的asynchronous函数,我们可以在javascript中使用构build块来构build我们自己的asynchronous函数。 这样的函数的例子包括http.request()方法, socket.listen()方法,可能是最简单的setTimeout()setInterval()

下面是一个例子,说明如何重写你的代码来实现asynchronous处理。

 function long_task (repeat_number, callback) { // setTimeout is asynchronous, so keep calling it until we're done function loop () { if (repeat_number > 0) { repeat_number --; setTimeout(loop,1); } else { callback("I'm done!"); } } loop(); } console.log("calling long task"); long_task(10000,function(x){console.log(x)}); console.log("long task started"); 

这是一个完全同步的代码,而node.js是单线程的,所以不会以这种方式启动第二个线程。

有几个asynchronous任务,如networking请求或数据库调用,但这不是。

你将不得不派生一个subprocess来使这个asynchronous。

有关更多信息,请参阅http://nodejs.org/api/child_process.html