![]() |
VOOZH | about |
Control flow is a fundamental concept in programming that determines the order in which code statements and function calls are executed. By controlling the flow of a program, you can create complex logic, handle different execution paths, and manage the sequence of function calls. Understanding control flow is crucial for writing efficient and maintainable code.
This article explores how control flow controls function calls in programming, covering key concepts, common patterns, and practical examples.
Table of Content
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a programming language. Control flow mechanisms allow a program to make decisions, repeat operations, and jump to different sections of code based on certain conditions.
if, else if, and else statements allow code to be executed based on specific conditions.for, while, and do...while loops enable repetitive execution of code blocks.try, catch, and finally blocks manage errors and exceptions in the program.Function calls are integral to the control flow in programming. They enable modular and reusable code. By controlling when and how functions are called, you can manage the complexity of your program.
In sequential execution, functions are called one after another in the order they are written.
Hello Goodbye
Note: In this example, greet() is called first, followed by farewell(), resulting in the output
Functions can be called conditionally based on the outcome of conditional statements.
Operation successful
Note: If operationSuccess is true, showSuccessMessage() is called. Otherwise, showErrorMessage() is called.
Control flow in Node.js is typically managed using one of three methods: callbacks, promises, and async/await.
Callbacks are functions that are passed as arguments to other functions and are executed when that function completes its task. In Node.js, many functions are asynchronous, and they often take a callback as an argument. When the asynchronous operation is completed, the callback is executed, allowing the program to continue its execution.
function functionName(param1, param2, callback){
// Asynchronous operation
callback(result);
}
Example 1: Implementation to show the use of callback with an example.
Callback Ans: 6
In the above example, the multiply function takes two numbers as arguments and a callback function that is executed when the multiplication is complete. The callback function simply logs the result to the console. The arrow function syntax is used to define the multiply function and the callback function.
Example 2: Implementation to show the use of callback with an example.
Fetched data: { id: 74, name: 'Geeks for Geeks' }In the above example, the fetchData function simulates an asynchronous operation (like making an API request) by using setTimeout. After the simulated delay, it invokes the callback function callback with the fetched data. The callback function handleData receives the fetched data and performs some operations with it. In this case, it logs the data to the console. When we call the fetchData function, we pass the URL, and the callback function handleData.
Promises in JavaScript are used to manage asynchronous operations more effectively compared to traditional callbacks. They represent a value that will be available in the future. When the value is ready, the promise is either fulfilled or rejected, triggering the corresponding code execution. This helps avoid "callback hell" and makes code more readable and maintainable. Promises are created using the `Promise` constructor, which accepts a function defining the operation. Once the operation completes, the promise is either resolved or rejected. Promises support chaining with the `.then()` method, facilitating the creation of complex workflows.
function functionName(){
return new Promise(function(resolve, reject){
// Operation
});
}
functionName()
.then(result)
.catch(error);
Example 1: Implementation to show the use of promises with an example.
Promise Ans: 5
In the above example, the divide function returns a promise that resolves to the result of dividing a by b. If b is zero, the promise is rejected with an error message. Then the promise is used in the then method to handle the fulfillment of the promise (i.e. when the result is available) and the catch method is used to handle the rejection of the promise (i.e. when an error occurs). In this case, the result of the division is logged into the console.
Example 2: Implementation to show the use of promises with an example.
User: { id: 74, name: 'Geeks for Geeks' }async/await in Node.js simplifies asynchronous code to look and behave more like synchronous code, enhancing readability and maintainability. Marking a function with async makes it return a promise, while await pauses execution within the async function until the awaited promise resolves or rejects, returning its value. This approach avoids the complexity of nested callbacks and makes asynchronous code easier to manage compared to traditional callbacks or promises.
async function functionName(){
await wait(ms);
}
functionName().catch(() => {});
Example 1: Implementation to show the use of async await with an example.
Async/await Starting... One second has passed! Two more seconds have passed!
In the above example, we define a wait function that returns a promise that resolves after a given amount of time (in milliseconds). We then define an example async function that uses await to pause execution until the promises returned by the wait function have resolved. When the example is called, it logs a message, waits for one second, logs another message, waits for two more seconds, and logs a final message. Because we are using async and await, we don't have to use callbacks or chain promises together, which can make our code more readable and easier to reason about.
Example 2: Implementation to show the use of async await with an example.
Async/await Sum is: 5
In the above example, the add function is marked as async, indicating that it returns a promise. The run function is also marked as async, and it uses the await keyword to wait for the promise returned by add to resolve before continuing execution.
Overall, in Node.js, the control flow of function calls can be managed using callbacks, promises, or async/await, depending on the specific needs and requirements of the program. These mechanisms provide a powerful and flexible way of managing the flow of function calls, allowing Node.js developers to build highly efficient and scalable applications.