Pages

Showing posts with label flow control. Show all posts
Showing posts with label flow control. Show all posts

[NodeJS] How to behave synchronously in an asynchronous world

Dispite the power of asynchronous programming in Javascript, there's time when you want to execute code synchronously. An example is when you have an array of tasks that must be completed sequentially. In this post, we are going to look at different ways to implement this in NodeJS.

Settings

Image you want to simulate the activities in a restaurants. The tasks are: server takes order, chef cooks, server serves food, customers enjoy the food. Since the level of details of simulation can be expanded in the future, we'll maintain an array of all the tasks and pass it to a task runner to handle the tasks.


function order() { console.log('Server gets order.'); }
function cook() {
  fs.readFile('cookbook.txt', function() {
    console.log('Chef cooks food.');
  };
}
function serve() { console.log('Server serves food.'); }
function dine() { console.log('Customers enjoy food.'); }

function run(tasks) {
  // run tasks
}

var tasks = [order, cook, serve, dine];
run(tasks);

As you can see, among these tasks, cook is the longest one because chef must find the recipe in a cookbok before starting to cook. Obviously, it's not a very good restaurant as you can tell but you get the idea.