Quick Index
Overview


This experiment will mix theory and practice.

Our goal is to (relatively quickly) get a good understanding of the core concept of asynchronous computing, which is sometimes elusive.

Hints:


Setup


Project Directory
Create a new project directory named "sync-async".

The remainder of our work will be in this directory.
/sync-async
names1.txt
Create a text file named "names1.txt".

Put any names/content you like into the file and save.
Asha
Wilma
Zandra
names2.txt
Create a text file named "names2.txt".

Put any names/content you like into the file and save.
Bob
Kofi
Mark
Report File
Create a new report text file named "sync-async.txt". Enter the two labels as shown.
file: sync-async.txt

** Synchronous Computation **



** Asynchronous Computation **


Synchronous Experiment


Before tackling asynchronous, we'll look at the simpler and more familiar synchronous computing.

Code for Experiment
Save this Node.js source into a file named "sync.js".

This code reads two files and logs (prints to console) status messages.
const
	fs = require('fs'),
	path1 = 'names1.txt',
	path2 = 'names2.txt',
	log = (obj) => console.log(obj.toString());

let fileContents1, fileContents2;

log('starting tasks');
log(`started reading ${path1}`);
fileContents1 = fs.readFileSync(path1);
log(`started reading ${path2}`);
fileContents2 = fs.readFileSync(path2);
log('finished tasks');
> node sync
Observations
Observe the output.

Jot (into your report file) down a few basic observations. Do both file reads appear to run at the same time? Does the computation wait at any point?

Note: your report can be short -- a few lines.

Note that you may like to tweak the experiment, e.g., adding more log lines, etc.
log('starting tasks');
etc.


Asynchronous Experiment


Code for Experiment
Save this Node.js source into a file named "async.js".

This time, you'll need to log (print to console) your own status messages. It may take a few runs to get them into the locations that give you the most helpful output.

hints
  • Add status messages in each callback function as well as in the main code
  • You may be able to find a strategic location to print a courtesy message like "please wait..."
const
	fs = require('fs'),
	path1 = 'names1.txt',
	path2 = 'names2.txt',
	log = (obj) => console.log(obj.toString());
	
const callbackFct1 = (err, aFileContents) => {
	if (err) throw err;
}

const callbackFct2 = (err, aFileContents) => {
	if (err) throw err;
}

fs.readFile(path1, callbackFct1);
fs.readFile(path1, callbackFct2);
> node sync
Observations
Observe the output.

Jot (into your report file) down a few basic observations. Do both file reads appear to run at the same time? Does the computation wait at any point?

Note that you may like to tweak the experiment, e.g., adding more log lines, etc.
log('starting tasks');
etc.


Review Observations


Review your observations vs similar experiments and definitions like these...

Tweak your report if you like.

Submitting