JavaScript 是單線程的程式語言,為了避免程式阻塞,多鼓勵使用非同步的 API 來進行操作,但非同步的 API 是否都能夠避免阻塞呢?到底非同步、單執行緒這之間的關係是什麼?在場短講中,將釐清這些每天在用卻可能似懂非懂的概念
用錯非同步,服務一樣會卡住陳柏融
View Slide
Javascript is a single threaded language
single thread 代表什麼
圖片來源:https://bytearcher.com/articles/parallel-vs-concurrent/Concurrency Parallelismsingle thread
那為什麼服務不會卡住?
因為有 Event Loop
圖片來源:https://zhuanlan.zhihu.com/p/34229323大神在此專注在這特別留意這裡的setTimeout 和Promise
那如果是耗能的 I/O 操作呢
圖片來源:https://nexocode.com/blog/posts/behind-nodejs-event-loop/大神在此專注在這
readFile 有兩種版本:非同步 vs. 同步
所以 Node.js 的 API 都鼓勵使用非同步的方法,好像後面有個大神會幫忙做事
所以只要有了非同步和 event loop,就不用擔心 JavaScript single thread 的問題嗎?
放在 Promise 的 then 之後?大神會來嗎?
大神會來嗎?把東西都包到 Promise 裡?
大神會來嗎?使用 setTimeout
把東西都包到 Asyc/Await 裡?大神會來嗎?
你覺得呢?
實際來看一下 server 卡住會怎麼樣吧
醒醒吧!你不是大神!
圖片來源:https://zhuanlan.zhihu.com/p/34229323大神在此但你在這
你看得到的程式碼大部分都會回到 single thread 中被執行
我要換語言了嗎!?
等等,你也可以是大神!
圖片來源:https://nexocode.com/blog/posts/behind-nodejs-event-loop/大神在此你也可以在這
開啟 Node.js 的 multi-thread
app.jsworker.js專案網址:https://github.com/pjchender/jsdc-2020
專案網址:https://github.com/pjchender/jsdc-2020
回到前端一樣也有 web worker 可用
開啟 worker 後避免畫面卡頓專案網址:https://pjchender.github.io/web-worker-example/
找到適合的地方,試著用用看 Worker 吧
參考連結- Node.js Worker threads 範例專案:https://github.com/pjchender/jsdc-2020- Web Worker 範例專案:https://github.com/pjchender/web-worker-example- Node.js Worker threads 官方文件- Using Web Workers @ MDN: