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框架和库.模 ...
随机推荐
- SpringBoot yaml的配置及使用
application.yml配置如下 person: lastName: hello age: boss: false birth: // maps: {k ...
- vue api
1. vue.config.silent = true 取消 Vue 所有的日志与警告. 2.vue.config.productionTip= false 设置为 false 以阻止 vue 在启动 ...
- How to put username &password in MongoDB(Security&Authentication)?(配置用户认证在MongoDB)
Default do not need username and password authenticate when access mongoDB ,I want to set up the use ...
- noip模拟赛 戏
[问题背景]zhx 和他的妹子(们) 做游戏.[问题描述]考虑 N 个人玩一个游戏,任意两个人之间进行一场游戏(共 N*(N-1)/2 场),且每场一定能分出胜负.现在, 你需要在其中找到三个人构成“ ...
- 四则运算结对编程(GUI)
四则运算GUI coding地址:https://git.dev.tencent.com/qyj814/GUI.git 结对伙伴:李梦宇 一.题目要求 定制出题要求.每次出题时用户都可以在界面上定制如 ...
- Sublime Text 3配置支持Markdown编辑
继上一篇http://www.cnblogs.com/EasonJim/p/7119304.html文章安装好之后,对Markdown支持需要做如下处理: 1.按下[Ctrl]+[Shift]+[P] ...
- 微软消息队列MessageQueue(MQ)
首先本地安装微软的消息队列服务器. 基础类: namespace Core.MessageQueueTest { public class TestQueue : IDisposable { prot ...
- 函数操作(this操作)
1.apply/call函数:会改变this关键字,并且第一个参数作为this关键字. /*apply与call区别*/ console.log(Array.prototype.join.call([ ...
- 1.7-BGP②
BGP的更新源(BGP Neighbor Update Source Address): 原则1: 在默认情况下, BGP路由器以自己路由表中,到达对方BGP邻居的地址的那条路由所指示的出接口(物理接 ...
- 1.3-动态路由协议RIP①
Dynamic Routing Protocol:动态路由协议 现代IP网络中,主要的动态路由协议: AD/管理距离: 1:DV/距离向量协议:RIP(120)/IGRP(100) 2:LS/链路状态 ...