node.js在windows下的學習筆記(4)---同步,非同步,回調的概念

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   ar   2014   

Node.js是使用事件驅動的,非阻塞的I/O模型,用於構建快速的,可擴充的網路應用程式。

Node.js想解決的問題是:處理輸入,輸入,高並發

1.阻塞與非阻塞

阻塞也叫同步,是指每一次執行一個操作,在這個操作完成之前,代碼的執行會被阻塞,無法移到下一個操作上。

阻塞就相當於你在超市裡面買東西,結賬,在排隊,如果前面的人沒買單,你就不能買,一定要等前面的人先執行完其操作才可以

非阻塞就相當於你在外婆家取號,然後就可以去幹別的事情了,等輪到我們的時候,簡訊發到我們的手機上了,說輪到我們了,這樣我們就可以回去吃飯了。

function sleep(milliseconds) {  var start = new Date().getTime();  while ((new Date().getTime() - start) < milliseconds){  }}function fetchPage() {  console.log(‘fetching page‘);  sleep(2000); // simulate time to query a database  console.log(‘data returned from requesting page‘);}function fetchApi() {  console.log(‘fetching api‘);  sleep(2000); // simulate time to fetch from an api  console.log(‘data returned from the api‘);}fetchPage();fetchApi();

執行上面的代碼結果如下:

Node.js幾乎不使用這種編碼風格,而是非同步地調用回調

什麼是回調呢?回調指的是將一個函數A作為參數傳遞給另一個函數B,並且通常在函數B完成後被調用。

                   1.非同步地調用是由作業系統在後台進行相應的操作。

                   2.同步的代碼會繼續執行

                   3.當作業系統非同步完成之後,調用回呼函數來進行相應的結果展示

var http = require(‘http‘)function fetchPage() {  console.log(‘fetching page‘);  http.get({ host: ‘trafficjamapp.herokuapp.com‘, path: ‘/?delay=2000‘ }, function(res) {    console.log(‘data returned from requesting page‘);  }).on(‘error‘, function(e) {    console.log("There was an error" + e);  });}function fetchApi() {  console.log(‘fetching api‘);  http.get({ host: ‘trafficjamapp.herokuapp.com‘, path: ‘/?delay=2000‘ }, function(res) {    console.log(‘data returned from the api‘);  }).on(‘error‘, function(e) {    console.log("There was an error" + e);  });}fetchPage();fetchApi();

非阻塞(非同步)的代碼執行的結果如下:

node.js在windows下的學習筆記(4)---同步,非同步,回調的概念

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.