Deep dive into JS asynchronicity

Single thread JavaScript

JavaScript has a concurrency model based on event loop. Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).

runYourScript(); 
while (atLeastOneEventIsQueued) {
    fireNextQueuedEvent();
};

Let's use setTimeout as a simple example:

let start = +new Date;
setTimeout(function Task1(){
    let end = +new Date;
    console.log(`Task1: Time elapsed ${end - start} ms`);
}, 500); //500ms later,Task1 will be inserted into event queue

// single thread
setTimeout(function Task2(){
    let end = +new Date;
    console.log(`Task2: Time elapsed ${end -start} ms`);
    /**
     * use while loop to delay the completion of the function for 3 seconds
     * this will block the execution of the next function in event loop
     * i.e. looping through the event queue has to happen after the main thread finishes its task
     */
    while(+new Date - start < 3000) {}
}, 300); //300ms later,Task2 will be inserted into event queue

while(+new Date - start < 1000) {} //main thread delay completion for 1 second
console.log('main thread ends');
//output: 
//main thread ends
//Task2: Time elapsed 1049 ms
//Task1: Time elapsed 3000 ms

setTimeout will put the first argument(type Function) into event queue. Here is what happens in the code above:

  • 300ms later,Task2 is inserted into event queue.
  • 500ms later,Task1 is inserted into event queue.
  • 1 second later, the main thread finishes, "main thread ends" is printed on the console.
  • The main thread will loop through the event queue when it finishes its job at hand. The first function in the event queue is Task2(as it's inserted first). So Task2 is fetched and executed, resulting the console output "Task2: Time elapsed 1049 ms". The elapsed time you see may differ as setTimeout is not exactly dealying the execution of your function. All it does is to put the function into the event queue with the delay you set. When the function will be executed depends on the queueing functions in the event queue, as well as the status of the main thread (whether it has remaining task running).
  • Execute Task1 after Task2 finishes.

What are Asynchronous functions

Asynchronous functions in JavaScript usually can accept a last parameter of function type (it's usually called callback) and the callback will be inserted into event queue when the function completes. As the callback is in event queue, the function is NON-BLOCKING. Asynchronous functions can guarantee the following unit test will always pass:

let functionHasReturned = false; 
asyncFunction(() => {
    console.assert(functionHasReturned); 
}); 
functionHasReturned = true;

Note that NOT all functions with a callback parameter are asynchronous. E.g. Array.prototype.forEach is synchronous.

let before = false;
[1].forEach(() => {
    console.assert(before); 
}); 
before = true;

Exceptions in asynchronous functions

Since the callback function is put in the event queue and executed later with it's own invoking context, wrapping the asynchronous functions with try-catch mechanism won't be able to catch the exception from the callback.

try {
    setTimeout(() => {
        throw new Error('callback error'); 
    }, 0);
} catch (e) {
    console.error('caught callback error');
}
console.log('try-catch block ends');

In the example, the exception thrown in the callback is not caught by our own program (i.e. the catch block - no 'caught callback error' is printed on the console). We can catch these uncaught exceptions with window.onerror in brower and process.uncaughtException in Node.

If we want to deliberately catch the error, as we should always do, we can do it in the callback. E.g.

let fs = require('fs'); 
fs.readFile('abc.txt', function(err, data) {
    if (err) {
        return console.error(err); 
    }; 
    console.log(data);
});

Reference

Notice

  • If you want to follow the latest news/articles for the series of reading notes, Please 「Watch」to Subscribe.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,012评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,628评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,653评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,485评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,574评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,590评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,596评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,340评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,794评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,102评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,276评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,940评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,583评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,201评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,441评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,173评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,136评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,319评论 0 10
  • 她是我去4s店认识的一个销售,其实算不上认识,她接待的我,介绍了车型,留了微信,后来再也没有联系过,仅此而已。后来...
    面包师的故事阅读 201评论 0 0
  • (对话方塘边那棵老杨树) 过两天就是新年,与你聊柴米油盐。 任凭它风吹雨打,棉田间把我遥望。 家里家外不见闲,我却...
    缤纷纤尘阅读 236评论 0 1
  • 也许你是看到标题过来的,或许是看到图过来的,或许偶然点开看的,没关系,来者都是客,也是一种缘分。 嗯,你没看错,是...
    峦天阅读 8,902评论 0 2
  • 心绪不宁添愁 生出物是人非的怅惘
    酌酒凭栏心澜言阅读 50评论 0 0