Questions And Answers

More Tutorials

NodeJS Synchronous vs Asynchronous programming

Using async

The async package provides functions for asynchronous code.

Using the auto function you can define asynchronous relations between two or more functions:

var async = require('async');{
 get_data: function(callback) {
 console.log('in get_data');
 // async code to get some data
 callback(null, 'data', 'converted to array');
 make_folder: function(callback) {
 console.log('in make_folder');
 // async code to create a directory to store a file in
 // this is run at the same time as getting the data
 callback(null, 'folder');
 write_file: ['get_data', 'make_folder', function(results, callback) {
 console.log('in write_file', JSON.stringify(results));
 // once there is some data and the directory exists,
 // write the data to a file in the directory
 callback(null, 'filename');
 email_link: ['write_file', function(results, callback) {
 console.log('in email_link', JSON.stringify(results));
 // once the file is written let's email a link to it...
 // results.write_file contains the filename returned by write_file.
 callback(null, {'file':results.write_file, 'email':''});
}, function(err, results) {
 console.log('err = ', err);
 console.log('results = ', results);

This code could have been made synchronously, by just calling the get_data, make_folder, write_file and email_link in the correct order. Async keeps track of the results for you, and if an error occurred (first parameter of callback unequal to null) it stops the execution of the other functions.


In this page (written and validated by ) you learned about NodeJS Synchronous vs Asynchronous programming . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS Error Management.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.