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阅读原文】。感谢您的支持!

您可能感兴趣的

NodeJS gm resize and pipe to response Is there a way of piping the resized image to my express response? Something along the lines of: var exp...
Node.js Admin Panels – Strapi and Express Ad... Lately, I’ve been researching for a fast and simple way to develop a back office in JavaScript, without the need to wri...
feflow:使用 Node.js 编写的致力于提升研发效率和规范的工程化解决方案... 致力于提升研发效率和规范的工程化解决方案,使用 Node.js 编写. 特性 强大的插件机制,易于扩展. 和Yeoman集成,很容易通过Yeoman脚手架进行项目的初始化创建. 支持多种主流构建,包...
Insights from an Open-Source Survey A few weeks ago, we wrapped up a small survey on open-source software. The survey was focused on OSS and Node.js usage a...
NodeJS getting and passing variables I am having some trouble figuring out variables "passing" (I know it's not the right term, I'll explain), given the asy...