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的更多相关文章

  1. How does a single thread handle asynchronous code in JavaScript?

    原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript ----------- ...

  2. How can I create an Asynchronous function in Javascript?

    哈哈:)我的codepen 的代码笔记是:http://codepen.io/shinewaker/pen/eBwPxJ --------------------------------------- ...

  3. Asynchronous programming in javascript

    Javascript是单线程的,因此异步编程对其尤为重要. ES 6以前: * 回调函数* 事件监听(事件发布/订阅)* Promise对象 ES 6: * Generator函数(协程corouti ...

  4. Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises

    非常好的文章,讲javascript 的异步编程的. ------------------------------------------------------------------------- ...

  5. [转]How WebKit’s Event Model Works

    原文:https://homes.cs.washington.edu/~burg/projects/timelapse/articles/webkit-event-implementation/ Fi ...

  6. Promise & Deferred objects in JavaScript Pt.1: Theory and Semantics.

    原文:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semanti ...

  7. JavaScript单元测试工具-Jest

    标注: 首先这并不是一篇完整的关于Jest的教程,只是个人在接触jest学习的一点随手笔记,大部分内容都是对官方文档的一些翻译. ----------------------------------- ...

  8. 每个JavaScript开发人员应该知道的33个概念

    每个JavaScript开发人员应该知道的33个概念 介绍 创建此存储库的目的是帮助开发人员在JavaScript中掌握他们的概念.这不是一项要求,而是未来研究的指南.它基于Stephen Curti ...

  9. JavaScript资源大全中文版(Awesome最新版)

    Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...

随机推荐

  1. 配置Struts2后运行jsp出现404的解决方法

    更新:善用控制台查看错误信息 --------------------------------------------- 原因:Java Build Path没有导入正确的jar包或者导入了但没有把相 ...

  2. 10 Python中的代码缓存机制

    目录: 1) 什么是代码块 2) 基本原理 3) 机制适用范围 4) 适用对象 5) 优势 更详细说明,参考太白老师博客 https://www.cnblogs.com/jin-xin/article ...

  3. Boundary Conditions

    test test Table of Contents 1. Boundary conditions 1.1. Neumann boudary condition vs Dirichlet BC 1. ...

  4. 在vue项目中快速使用element UI

    推荐使用npm安装 1.安装:npm install element-ui -S 2.整体引入: 在你项目的main.js中写入: import ElementUI from 'element-ui' ...

  5. Andrew and Chemistry(树的同构)

    Andrew and Chemistry(树的同构) 题链 将一棵树转化为最小表示法,将此时的树哈希一下,同时用map进行标记,就可以判断树是否存在同构 #include <map> #i ...

  6. 【04】JSONP 教程

    JSONP 教程 Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据. 为什么我们从不同的域 ...

  7. CSS中具有继承性的属性:

    CSS中具有继承性的属性:   color:#eee font: font-style font-variant: font-weight:bold font-size font-family: fo ...

  8. noip模拟赛 轰炸

    题目描述 C国和W国爆发了战争!YJC决定对W国的n个城市进行轰炸.每个城市都有一个重要度ai.设xi=‘重要度大于ai的城市数+1’,那么编号为i城市就是第xi个被轰炸的城市.显然这样能保证重要度大 ...

  9. Java中DAO/DTO/PO/VO/BO/QO/POJO

    ORM:是Object Relational Mapping(对象关系映射)的缩写. 通俗点讲,就是将对象与关系数据库绑定,用对象来表示关系数据.在O/R/M的世界里,有两个基本的也是重要的东东需要了 ...

  10. 改动wordpress默认发邮件邮箱地址

    方法一: wordpress发送邮件默认是用的php mail函数.所以发送邮件的地址是能够随意写的.其默认发邮件的地址是wordpress@yourdomain.com.当然这个地址是能够改动的. ...