Nodejs asynchronous confusion

综合技术 2018-05-26

I can't seem to grasp how to maintain async control flow with NodeJs. All of the nesting makes the code very hard to read in my opinion. I'm a novice, so I'm probably missing the big picture.

What is wrong with simply coding something like this...

function first() {
    var object = {
        aProperty: 'stuff',
        anArray: ['html', 'html'];
    };
    second(object);
}

function second(object) {
    for (var i = 0; i < object.anArray.length; i++) {
        third(object.anArray[i]);
    };
}

function third(html) {
    // Parse html
}
first();

Problem courtesy of: mnort9

Solution

The "big picture" is that any I/O is non-blocking and is performed asynchronously in your JavaScript; so if you do any database lookups, read data from a socket (e.g. in an HTTP server), read or write files to the disk, etc., you have
to use asynchronous code. This is necessary as the event loop is a single thread, and if I/O wasn't non-blocking, your program would pause while performing it.

You can
structure your code such that there is less nesting; for example:

var fs = require('fs');
var mysql = require('some_mysql_library');

fs.readFile('/my/file.txt', 'utf8', processFile);

function processFile(err, data) {
  mysql.query("INSERT INTO tbl SET txt = '" + data + "'", doneWithSql);
}

function doneWithSql(err, results) {
  if(err) {
    console.log("There was a problem with your query");
  } else {
    console.log("The query was successful.");
  }
}

There are also flow control libraries like async
(my personal choice) to help avoid lots of nested callbacks.

You may be interested in this screencast I created on the subject
.

Solution courtesy of: Michelle Tilley

Discussion

As @BrandonTilley said, I/O is asynchronous, so you need
callbacks in Node.js
to handle them. This is why Node.js
can do so much with just a single thread (it's not actually doing more in a single thread, but rather than having the thread wait around for the data, it just starts processing the next task and when the I/O comes back, then it'll jump back to that task with the callback function you gave it).

But, nested callbacks can be taken care of with a good library like the venerable async
or my new little library: queue-flow
. They handle the callback issues and let you keep your code un-nested and looking very similar to blocking, synchronous code. 🙂

Discussion courtesy of: David Ellis

This recipe can be found in it's original form on Stack Over Flow
.

您可能感兴趣的

Node.js and rails app hosting with a shared MongoD... I have been experimenting a lot with node.js as well as with rails and mongoDB lately. I'd like to know if there's any hosting options out there...
NodeJS and Socket.io I have just installed these nodejs and socket.io but I am having problems with getting the client to connect to the server. In my server I have: ...
Confused about node.js file system I used write file with nodejs in two steps: 1.First judge if the file is exist or not,use fs.exists function; 2.Then use ...
Node.js and MySQL function usage New to node.js and just cant figure out how to do the following: I have this on my db module: var mysql = require('mysql'); var MY_D...
Node.js with Handlebars.js on server and client I have an app in Node.js using Expressjs and Handlebars as the template engine. Expressjs uses layouts and then renders views. The layou...