![]() | 1 davepkxxx 2013-06-02 03:32:37 +08:00 和js的异步和回调不一样? |
![]() | 2 Ricepig 2013-06-02 06:23:09 +08:00 你就当它在某个时候(满足某个条件)就一定会调用就行,嘿嘿 |
![]() | 3 fangpeishi 2013-06-02 09:15:41 +08:00 “我不会等你,我先做我的,你继续做你的,等会我会向你要成果。” 这篇日记是不是有帮助呢? http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFJavascript.html 看里面解释的回调函数。 另外,看第一个例子就好了: http://www.infoq.com/cn/news/2011/09/nodejs-async-code |
![]() | 4 fatpa 2013-06-02 10:40:12 +08:00 当有异步通讯触发的时候就调用这个回调函数了,就像在C#里面是写一个委托去调用某个函数的,思路应该都差不多的 |
![]() | 5 kfll 2013-06-02 12:55:53 +08:00 在外部调用 console.log(a) 的话,这样: setInterval( function() { console.log(a) }, 100 ) 看日志你差不多就明白了 |
![]() | 6 bigmusic 2013-06-02 22:44:31 +08:00 |
![]() | 7 axqd 2013-06-03 08:55:11 +08:00 http.get(url,function(res){ 在这里获得某个数据a console.log(a) } |
![]() | 8 zhujinliang 2013-06-03 09:52:39 +08:00 回调函数而已。 function http_get_callback(res){ /// do something } http.get(url, http_get_callback); 这样写能看懂么 那么改成匿名函数再调一下位置呢 http.get(url, function(res){ /// do something }); |
![]() | 9 gdzdb 2013-06-03 16:32:29 +08:00 就是字面上的意思。 比如正常的流程是 A→B→C 其中A→B需要5分钟才能执行完的话,那么执行C就是5分钟后的事情了。 而异步就是 A→C → B 在B出结果前,直接先执行C,不用等5分钟,但是这样子的话C的执行环境就跟B是没有关系了。 发现越简单的道理越难解释~ |
10 JeremyWei 2013-06-03 22:20:46 +08:00 其实主要是event loop,看下这篇文章: http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ |
![]() | 11 heroicYang 2013-06-03 22:47:39 +08:00 简单回一个吧,回调函数就是你做完某事调我就行,这里面不一定涉及到异步。比如: function a (callback) { var now = new Date; while (new Date - now <= 5000) {} callback && callback(); } a(function () { console.log('callback'); }); 和 a(); console.log('callback'); 并没有扯到所谓的异步。 function b (doSomething, doAnother) { // 不好意思我要占用太久时间,doAnother你要等不及就先不管我吧 setTimeout(function () { var now = new Date; while (new Date - now <= 5000) {} doSomething && doSomething(); }, 0); doAnother && doAnother(); } b(function () { console.log('do something...'); }, function () { console.log('do another...'); }); 这里的doSomething和doAnother都是回调,但是它们在内部就是异步执行的了。。 异步编程主要就是解决等待问题... |
![]() | 12 heroicYang 2013-06-03 22:52:20 +08:00 ![]() 好吧代码格式乱完了,重新贴个截图吧。 ![]() |
![]() | 13 chemzqm 2013-06-03 23:11:20 +08:00 回调一般应该是在将来某个时候会执行,node里一般是触发IO事件的时候,这么做可以更有效利用系统调度,提高并发量。 |
![]() | 14 foru17 OP @heroicYang 多谢各位 |
![]() | 15 hustlzp 2013-06-04 18:47:31 +08:00 @heroicYang 这个字体是?感觉括号看起来蛮爽的~ |
![]() | 16 heroicYang 2013-06-04 23:34:45 +08:00 @hustlzp Monaco ~ |
17 judasnow 2013-07-04 12:40:45 +08:00 |