Synchronousand Asynchronous Programming - Copy
Synchronousand Asynchronous Programming - Copy
• Programs are executed in a sequential manner. Thus, one operation must be fully completed before the
next operation can begin.
• Tasks are executed in order, one after the other, and it cannot be interrupted until finished.
• Waits for a function to complete before moving on to the next line of code.
• Works best when tasks are short and straightforward enough so that there is no need to execute
multiple tasks simultaneously.
ADVANTAGES DISADVANTAGES
• It is a programming where code execution is separated into multiple tasks that can run independently
without waiting for one task to finish so that another can begin.
• It is possible by writing code split into smaller, independent tasks and running each task in its thread.
• By creating threads for each task, it makes it possible to do many tasks simultaneously by allowing them
to run in parallel.
• Once all the tasks are finished, they can synchronize to return a result.
• Works best when tasks are long, complex and require multiple supplies.
• For example, when a web application sends an asynchronous request to the server and multiple requests
can be executed concurrently. The application can continue to run while waiting for the response.
1. Callback functions
A callback function is passed as an argument to an asynchronous operation. When the operation is
complete, the callback function is called, often with the result if the operation is a parameter.
It allows a program to perform other tasks while waiting as to not block and wait for the operation to
finish.
2. Promises
Promises are another important concept in asynchronous programming. A promise is an object that
represents the eventual result of an operation. When a promise is created, it is pending and as the
operation progresses the promise is either fulfilled with a result or rejected with error. It is a bit like
callback functions.
3. Async/await
This is a newer syntax for asynchronous programming, that is built on top of promises. It provides a
simplified way to write asynchronous code that reads more like synchronous code. It returns promises
and can be used to wait for the resolution of a promise without blocking the program.
ADVANTAGES DISADVANTAGES
The choice depends on the goal of the program. If we need to complete tasks in a specific order and
time are not important, then synchronous programming is best.
However, if you need to execute multiple tasks simultaneously and need results of each task to continue
the program, the asynchronous programming is better.
CAMELCASE EXERCISE: