A Few Words on Callbacks and Asynchronous Mechanism In Javascript
It is said that the one of the most routine work a javascript programmer do is writing codes like "something.onclick= function(e){}". I myself have written thousands lines of codes like this. But one thing I was confused when first coming across with this type of code is: "something.onclick= function(e){}", wait...where does the e come from, who provided it? Somebody also write it as 'event' or 'evt', are there any differences between them?
Well, if you also think in this way, then you should take some time to learn something about Callbacks and Asynchronous Mechanism In Javascript. In fact, when you write something like "something.onclick= function(e){}". you think you were handling an event, but in fact, you are just delegate the event handler to the browser's javascript engine.
It's kind of Like you are saying: "Hey, javascript engine, to wait a user to click(or xhrs, or settimeouts) takes too long, i got a lot of other important stuff to do. so can you help me listen the user's click?"
the Javascript engine says :"no problem, but I don't know how should I do when the user clicks?"
you then write an function and give it to the Javascript engine. the function says: "if an event comes you should execute me with an 'event' argument, you should ckeck the event's type, then check event.pageX and blablabla..." Now I am clear: the event, evt or e we write is just a formal argument, so it doesn't matter how we write it, it is just a placeholder.
This story gives us a few insights about callbacks and asynchronous mechanism. That is, in Javascript, when you need to do some time-consuming operations, like xhr requests or settimeouts or user interactions, instead of just pending and wait while it is progressing, you can write a callback, which describes how the operation's result will be handled, and throw it to the javascript engine's async queue, and it will help you to monitor the event, and you just do anything else you want. Once the operations fulfilled,or the certain events happened, the engine will give the handler back to the bottom of main thread, if the main thread is not busy, the handler will be executed.
Notice here: When we say that "the engine will give the handler back to the bottom of main thread", we means that: as long as the main thread is busy, the handler will never be executed! That is to say: the handler executes only when:
1.asynchronous condition fulfilled.
2.main thread is free.
This leads us to a very interesting question, how will these codes outputs:
setTimeout(function(){
console.log('end');
},0);
console.log('starts');
Ofcourse, as the two words itself implies: the result will be starts -> end.Because the setTimeout function,(together with xhrs, on+'event') has a built-in implementation of Async.when we set timeouts to a function, instead of execute this function instantly, it will throw it to the async queue, and continue to execute other codes, once the async condition fulfilled, it throwes the function back to main thread.
meet setTimeout -> throw func to queue -> continue with console.log('starts')-> 0ms later,condition fulfilled ->throw back func -> executes func -> console.log('end').
Now that we have been familiar with this mechanism, we can use it write owesome codes.
In jQuery, we often write codes like:
//Pyramids of Doom :(
$.ajax('a.html', function(reseponseData){
$.ajax('b.html', responseData, function(yetAnotherData){
$.ajax('c.html', yetAnotherData, function(finalData){
handleTheData(finalData);
});
});
});
Is there any problem with these codes? nope, you say, it works well, I am using ajax callbacks to write interactive web pages! But there ARE problems.At least, Firstly, the codes expands horizontally faster than it expands vertically, our code become 'fat'. Secondly, every ajax call is dependent on previous call's response data, how could you elegantly catch errors between them?
This leads us to another hot topic in Javascript thesedays. It is the Promise.
A Few Words on Callbacks and Asynchronous Mechanism In Javascript的更多相关文章
- How does a single thread handle asynchronous code in JavaScript?
原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript ----------- ...
- How can I create an Asynchronous function in Javascript?
哈哈:)我的codepen 的代码笔记是:http://codepen.io/shinewaker/pen/eBwPxJ --------------------------------------- ...
- Asynchronous programming in javascript
Javascript是单线程的,因此异步编程对其尤为重要. ES 6以前: * 回调函数* 事件监听(事件发布/订阅)* Promise对象 ES 6: * Generator函数(协程corouti ...
- Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises
非常好的文章,讲javascript 的异步编程的. ------------------------------------------------------------------------- ...
- [转]How WebKit’s Event Model Works
原文:https://homes.cs.washington.edu/~burg/projects/timelapse/articles/webkit-event-implementation/ Fi ...
- Promise & Deferred objects in JavaScript Pt.1: Theory and Semantics.
原文:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semanti ...
- JavaScript单元测试工具-Jest
标注: 首先这并不是一篇完整的关于Jest的教程,只是个人在接触jest学习的一点随手笔记,大部分内容都是对官方文档的一些翻译. ----------------------------------- ...
- 每个JavaScript开发人员应该知道的33个概念
每个JavaScript开发人员应该知道的33个概念 介绍 创建此存储库的目的是帮助开发人员在JavaScript中掌握他们的概念.这不是一项要求,而是未来研究的指南.它基于Stephen Curti ...
- JavaScript资源大全中文版(Awesome最新版)
Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...
随机推荐
- Vue2 + Koa2 实现后台管理系统
看了些 koa2 与 Vue2 的资料,模仿着做了一个基本的后台管理系统,包括增.删.改.查与图片上传. 工程目录: 由于 koa2 用到了 async await 语法,所以 node 的版本需要至 ...
- sprintf用法
函数简介 函数功能:把格式化的数据写入某个字符串 头文件:stdio.h 函数原型:int sprintf( char *buffer, const char *format [, argument] ...
- SpringSecurity 获取认证信息 和 认证实现
JdbcDaoImpl 实现获取认证信息 PasswordEncoder 实现具体认证过程
- java 访问对象私有变量
Captcha captcha = getCaptcha(captchaId); // 通过反射获取验证码值 Class<?> classType = captcha.getClass() ...
- POJ3624 0-1背包(dp+滚动数组)
Charm Bracelet Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 47440 Accepted: 20178 ...
- nyoj 93 汉诺塔(三)(stack)
汉诺塔(三) 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 在印度,有这么一个古老的传说:在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针.印度 ...
- noip模拟赛 whzzt-Warmth
分析:这道题难度和天天爱跑步差不了多少啊......裸的暴力只有10分,最好大的还是那个5%的数据,不过这也才15分,比天天爱跑步的暴力分不知道少到哪里去了. 正解是dp,毕竟要求方案数嘛,但是这个d ...
- [K3Cloud2.0]如何解决创建管理中心失败的问题
标题有点大,实际上,Cloud2.0产品质量还是顶呱呱的,至于在安装使用过程中出现的这个管理中心无法创建的问题,实际上是与我的网络环境有关,下面讲一下我的网络环境: 开发团队目前所在网段:10.30. ...
- PayPal加密证书.pem的生成
How do I create a public certificate for use with PayPal Encrypted Website Payments? Before you ca ...
- [JavaEE] Create API documents with Swagger
We mainly need to modify our Model and REST endpoint code to enable swagger Document. model/Book.jav ...