es6 generator for asynchronous control flow

In node.js, input and output operations are asynchronous or non-blocking I/O. It allows other operations to continue before the I/O transmission are finished. For example, when it encounters a file read operation, it will not wait for the file reading operation to finish, but instead it will jump to the next line of code and go on it’s execution. This causes the results of the I/O operation to be out of order. There are ways of to control the order, such as nested callback function, async libraries, promise libraries and generator function. Generator function is a new feature in es6, the snippet below is an example of using generator function to make sure the asynchronous functions to run in the order it is written in the code.

// ssynchronous timeout function
// genAsync is a generator object in global scope
// genAsync.next in this function keeps the tasks to run till completed
function timeoutFunc(order) {
	var random = Math.random();
	setTimeout(function(){
		genAsync.next(random + order);
	}, random * 3000);
}

// The generator function runing the asynchronous function in series, one after another
function* runTimeoutFuncAsync() {
	var random1 = yield timeoutFunc(1); console.log(random1);
	var random2 = yield timeoutFunc(2); console.log(random2);
	var random3 = yield timeoutFunc(3); console.log(random3);
}
var genAsync = runTimeoutFuncAsync();
genAsync.next(); // kick off the tasks

Search within Codexpedia

Custom Search

Search the entire web

Custom Search