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框架和库.模 ...
随机推荐
- 14mysql事务、数据库连接池、Tomcat
14mysql事务.数据库连接池.Tomcat-2018/07/26 1.mysql事务 事务指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部不成功. MySQL手动控制事务 开启事 ...
- Python面向对象,析构继承多态
析构: def __del__(self): print("del..run...") r1 = Role("xx") del r1 结果打印del..run. ...
- LES on Wind turbine
- 关于vuex自己理解的三幅图
- 2.8 补充:shell变量引用方式
一 变量 变量:本质上是程序中保存用户数据的一块内存空间,变量名就是内存空间地址. Shell中:变量可由字母数字和下划线组成,以字母或下划线开头. 命名:PATH=/sbin ...
- angular中多个promise的合并处理
all()方法 这个all()方法,可以把多个primise的数组合并成一个.当所有的promise执行成功后,会执行后面的回调.回调中的参数,是每个promise执行的结果.当批量的执行某些方法时, ...
- java8 新特性 lambda过滤
1. 定义实体类 package com.atguigu.java8; public class Employee { private int id; private String name; pri ...
- textarea 高度调整
textarea 高度调整 通过 rows 属性调整 高度
- android保存bitmap到sdcard
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //判断sdcard是否存在和是否具有读写 ...
- 母函数(Generating function)详解
母函数(Generating function)详解 在数学中,某个序列的母函数(Generating function,又称生成函数)是一种形式幂级数,其每一项的系数可以提供关于这个序列的信息.使用 ...