Regular functions execute from start to finish sequentially. Once a function is called, it runs continuously until it either hits a return statement or reaches the end of its body.
A basic demonstration:
function someRegularFunction() {
console.log("1");
console.log("2");
console.log("3");
}
someRegularFunction();
// Output will be as follows:
// 1
// 2
// 3
In the snippet above, when the function is called, it executes each line in a linear manner (by order they were defined) and it is reflected in the output.
Generator functions are a special types of functions in JavaScript, introduced in ES6, that have the built-in capability to be paused and resumed allowing us to take control of the execution flow and generate multiple values.
The syntax, as shown below, is pretty much similar with regular functions apart from the new function* keyword.
Like this:
function* someGeneratorFunction() {
// function code goes here
}
Generator Functions implement the yield keyword which allows them to pause execution and produce values. Yielding a value from the function both saves its state and creates the ability to resume execution at any time through the next() method.
function* someGeneratorFunction() {
console.log("Start of the function");
yield 1;
console.log("Middle of the function");
yield 2;
console.log("End of the function");
}
const generator = someGeneratorFunction(); // Returns generator object
console.log(generator.next().value);
// Start of the function
// 1
console.log(generator.next().value);
// Middle of the function
// 2
console.log(generator.next().value);
// End of the function
// undefined
In the snippet above, calling the generator function someGeneratorFunction* returns a generator object. On this object, we can call the next() method, which will cause the generator function to execute. If a yield is encountered, the method returns an object that contains a value property containing the yielded value and a boolean done property which indicates if the generator has yielded its last value or not.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.