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'];

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

function third(html) {
    // Parse html

Problem courtesy of: mnort9


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


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 Recipes

责编内容by:Node.js Recipes阅读原文】。感谢您的支持!