᳓前言
非同步(Asynchronous)作為Node.js的一大特點,很難經由一篇文章便完全說明其精髓,預計整理出一系列文章並陸續發佈。
᳓重點整理
- 同步(Synchronous):在程式碼執行過程中,必須依照編寫的順序執行,當一行程式碼執行完畢並傳回其結果之後,才會執行下一行程式碼。
- 非同步(Asynchronous):與同步相反,當一行非同步的程式碼開始執行後,可以馬上接著執行下一行程式碼,不會耽誤後續程式碼的執行。而當該非同步的程式碼執行完畢後,可透過callback function傳回其結果,接著執行後續對應的程式碼。
- 在Node.js中,並不是全部的function都能夠以非同步的方式執行。
᳓實作
Synchronous的寫法:
Asynchronous的寫法:
᳓其他參考文章
佳魁資訊所出版"為什麼全世界都在學Node.js"
Synchronous的寫法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Display an console log after 3 seconds (3000 milliseconds) | |
* 功能:三秒後顯示一行字 | |
* | |
*/ | |
let waitSeconds = function(callback, seconds){ | |
let diff = 0; | |
let sDate = new Date(); | |
while(diff < seconds){ | |
let eDate = new Date(); | |
diff = eDate - sDate; | |
} | |
callback(); | |
} | |
let wait = function(){ | |
console.log("after 3 seconds! " + new Date()); | |
} | |
console.log("Start. " + new Date()); | |
waitSeconds(wait, 3000); // 等待三秒後輸出 | |
console.log("End. " + new Date()); // 由於waitSeconds並不是非同步函數,因此程式碼照順序執行,導致這行為三秒後輸出 |
執行結果 |
Asynchronous的寫法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Display an console log after 3 seconds (3000 milliseconds) using asynchronous function | |
* 功能:三秒後顯示一行字 | |
* | |
*/ | |
let wait = function(){ | |
console.log("after 3 seconds! " + new Date()); | |
} | |
console.log("Start. " + new Date()); | |
setTimeout(wait, 3000); // 等待三秒後輸出 | |
console.log("End. " + new Date()); // 由於setTimeout是非同步函數,因此執行的同時便接著執行這行,導致這行沒有等待便輸出 |
執行結果 |
᳓其他參考文章
佳魁資訊所出版"為什麼全世界都在學Node.js"
沒有留言:
張貼留言