asynchronous - node.js: confusion with order of callbacks -


i have started node.js. find asynchronous coding style uses impressive indeed. however, of used java , python take time used it.

i know following code works fine. verified several questions on forum. have tried on own.

var http = require('http'), fs = require('fs'); fs.readfile('./index.html', function (err, html) {     if (err) {         //throw err;      }            http.createserver(function(request, response) {          console.log("server started");         response.writeheader(200, {"content-type": "text/html"});           response.write(html);          response.write("other things");         response.end();       }).listen(3000); }); 

the way interpretting follows:

1. try reading html file    i. when done create server     ii. send on client 2. else. 

however, can have chain of thoughts follows:

1. create server 2. try reading file    i. when done. send on client 3. in meanwhile else server might asked do.  

the code corresponding second chain of thoughts is:

var http = require('http'), fs = require('fs');  http.createserver(function(request, response) {          console.log("server started");         response.writeheader(200, {"content-type": "text/html"});         fs.readfile('./index.html', function (err, html) {             if (err) {             //throw err;              }             response.write(html);             response.write("other things");         });         response.end();   }).listen(3000);  

while first code works expected. second 1 displays nothing @ in browser.

why second chain of thoughts wrong?

actually, happens here following function gets called each time there incoming request:

function(request, response) {      console.log("server started");     response.writeheader(200, {"content-type": "text/html"});       response.write(html);      response.write("other things");     response.end();   } 

you replaced with:

function(request, response) {      console.log("server started");     response.writeheader(200, {"content-type": "text/html"});     fs.readfile('./index.html', function (err, html) {         if (err) {         //throw err;          }         response.write(html);         response.write("other things");     });     response.end();   } 

now here, run following:

  1. write header
  2. queue readfile
  3. immediately execute following: response.end();
  4. by time done reading file , wants write contents, ended response

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -