了解回电 [英] Understanding Call backs

查看:89
本文介绍了了解回电的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个小脚本来更好地了解回调.

从下面的脚本中,我期望的行为是:"http.get运行,平均花费200毫秒.for循环" i的增量平均花费2500毫秒.在200毫秒时,该进程应退出并且该脚本应该停止工作了,为什么要打印所有的i?如果我对这更好理解,我想我也了解回调了.

  var http = require("http");var starttime = new Date();//带有回调的功能对于(var j = 0; j< 10; j ++){http.get({host:'nba.com'},function(res){console.log("Time Taken =",new Date()-starttime,'ms');process.exit();}).on('error',function(er){console.log('Got Error:',er.message);})}//超过回调触发时间的循环for(var i = 1; i< 10000; i ++){console.log(i);}console.log("Time Taken =",new Date()-starttime,'ms'); 

解决方案

node.js中的Javascript是单线程的,并且I/O是使用事件队列进行事件驱动的.因此,在您的Javascript原始线程完成并将控制权返回给系统之前,您的异步回调表明HTTP请求已完成,异步回调将无法运行,然后在该系统中它可以从事件队列中提取下一个事件以服务于HTTP请求的完成./p>

这样,您的 for 循环将在处理任何http响应之前运行完毕.

这是逐步的过程:

  1. 您的第一个 for 循环运行并发送10个http请求.
  2. 这些http请求使用异步网络在后台运行.当其中一个完成并有响应时,http模块会将事件放入Javascript事件队列中,当它完成其他活动后,将其从事件队列中拉出将是JS解释器的工作.
  3. 您的第二个 for 循环运行完成,并且所有 i 值都输出到控制台.
  4. 您的脚本完成了.
  5. 然后,JS解释器检查事件队列以查看是否有任何未决事件.在这种情况下,会有一些http响应事件.JS解释器从事件队列中提取最早的事件,并调用与此事件相关联的回调.
  6. 该回调完成后,将从事件队列中提取下一个事件,然后继续进行处理,直到事件队列为空.
  7. 如果您有任何回调调用 process.exit(),则这会短路其余的回调并立即退出该过程.

尽管其他答案是为浏览器编写的,但事件驱动的单线程概念与node.js中的相同,因此该其他答案可能为您解释了更多内容:JavaScript如何在后台处理AJAX响应?

I create a small script to understand callback better.

From the below script, the behavior I expected was: "http.get runs and takes on average 200 ms. The for loop "i" increment takes on average 2500 ms. At 200 ms, the process should exit and the script should have stopped to work. Why is it printing all of i? If I understand this better, I think I understand callback.

var http = require("http");
var starttime = new Date();

//Function with Callback
for (var j =0; j<10; j++){
    http.get({host : 'nba.com'}, function(res){
        console.log("Time Taken = ", new Date() - starttime, 'ms');

        process.exit();
    }).on('error', function(er){
        console.log('Got Error :', er.message);
    })
}

//Loop that exceeds callback trigger time
for(var i=1; i<10000; i++){
    console.log(i);
}

console.log("Time Taken = ", new Date() - starttime, 'ms');

解决方案

Javascript in node.js is single threaded and I/O is event driven using an event queue. Thus your async callbacks that signal the completion of the http requests cannot run until your original thread of Javascript finishes and returns control back to the system where it can then pull the next event from the event queue to service the completion of the http request.

As such, your for loop will run to completion before any http responses can be processed.

Here's the step by step process:

  1. Your first for loop runs and sends 10 http requests.
  2. These http requests run in the background using async networking. When one of them completes and has a response, the http module will put an event in the Javascript event queue and it will be the JS interpreter's job to pull that event from the event queue when it is finished with its other activities.
  3. Your second for loop runs to completion and all the i values are output to the console.
  4. Your script finishes.
  5. The JS interpreter then checks the event queue to see if there are any pending events. In this case, there will be some http response events. The JS interpreter pulls the oldest event from the event queue and calls the callback associated with that.
  6. When that callback finishes, the next event is pulled from the event queue and the process continues until the event queue is empty.
  7. If any of your callbacks call process.exit(), then this short circuits the remaining callbacks and exits the process immediately.

While this other answer was written for the browser, the event-driven, single threaded concept is the same as it is in node.js so this other answer may explain some more things for you: How does JavaScript handle AJAX responses in the background?

这篇关于了解回电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆