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 Recipes

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

您可能感兴趣的

How can I replicate the functionality of a wget wi... Is it possible to essentially run a wget from within a node.js app? I...
How does next() work in Node.js? I recently read a blog in Nodejitsu and I am wondering how this piece of c...
Does it make sense to minify code used in NodeJS? I was wondering, since Clojure Compiler and UglifyJS not only optimize code ...
June 2018 Security Releases Node.js will release new versions of all supported release lines on or around...
What would be the best possible way to generate AP... I am using my own authentication and sort of worried about the present security ...