0% found this document useful (0 votes)
0 views

Asynchronous Programming in JavaScript

Asynchronous programming in JavaScript allows multiple tasks to be executed simultaneously, improving performance and responsiveness by not waiting for one task to finish before starting another. It can be implemented using callbacks, which are functions executed after a task completes, or promises, which provide a more organized way to handle asynchronous operations with three states: pending, fulfilled, and rejected. Promises allow for attaching callbacks to handle outcomes and can be consumed using .then, .catch, and .finally methods for better readability and flow control.

Uploaded by

gatwirifloridah4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Asynchronous Programming in JavaScript

Asynchronous programming in JavaScript allows multiple tasks to be executed simultaneously, improving performance and responsiveness by not waiting for one task to finish before starting another. It can be implemented using callbacks, which are functions executed after a task completes, or promises, which provide a more organized way to handle asynchronous operations with three states: pending, fulfilled, and rejected. Promises allow for attaching callbacks to handle outcomes and can be consumed using .then, .catch, and .finally methods for better readability and flow control.

Uploaded by

gatwirifloridah4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Asynchronous Programming in JavaScript

To understand what asynchronous programming means, think


about multiple people working on a project simultaneously,
each on a different task.
In traditional (synchronous) programming, each person would
have to wait for the person before them to finish their task
before starting their own.
But with asynchronous programming, everyone can start and
work on their tasks simultaneously without waiting for the
others to finish.
Similarly, in a computer program, asynchronous programming
allows a program to work on multiple tasks simultaneously
instead of completing one task before moving on to the next
one. This can make the program get more things done in a
shorter amount of time.
For example, a program can send a request to a server while
handling user input and processing data, all at the same time.
This way, the program can run more efficiently.
Asynchronous programming is a way for a computer program
to handle multiple tasks simultaneously rather than executing
them one after the other.

Asynchronous programming allows a program to continue


working on other tasks while waiting for external events, such
as network requests, to occur. This approach can greatly
improve the performance and responsiveness of a program.
For example, while a program retrieves data from a remote
server, it can continue to execute other tasks such as
responding to user inputs.
Here's an example of an asynchronous program using
the setTimeout method:
console.log("Start of script");

setTimeout(function() {
console.log("First timeout completed");
}, 2000);

console.log("End of script");

In this example, the setTimeout method executes a function


after a specified time. The function passed to setTimeout will
be executed asynchronously, which means that the program
will continue to execute the next line of code without waiting
for the timeout to complete.
In JavaScript, asynchronous programming can be achieved
through a variety of techniques. One of the most common
methods is the use of callbacks.

How to Use a Callback Function


Let's say you want to plan a birthday party for your child. You
have to invite the guests, order a cake, and plan the games.
But you also want to hire a clown to entertain the guests. You
can only have the clown come to the party once all the other
party arrangements are done, and the guests have arrived.
So, you tell the clown to come to the party only after you
have notified him that the guests have arrived. In this case,
the clown represents a callback function, and the "guests
arriving" represents the function that has to complete
execution before the callback can be executed.
In code, a callback function is a function that is passed as an
argument to another function, and it is executed after the
first function has finished running. It's commonly used in
JavaScript to handle asynchronous operations like fetching
data from a server, waiting for a user's input, or handling
events.

function fetchData(callback) {

setTimeout(() => {
const data = {name: "John", age: 30};
callback(data);
}, 3000);
}

// Execute function with a callback


fetchData(function(data) {
console.log(data);
});
console.log("Data is being fetched...");

In this example:
 We have a function called fetchData that uses
the setTimeout method to simulate an asynchronous
operation. The function takes a callback as an argument.
 The callback function is then passed the data retrieved
by the function after the timeout has been completed.
This is the core concept of asynchronous programming. The
script doesn't wait for the asynchronous operation to
complete. It just continues to execute the next instruction.
Callbacks provide a useful way to handle asynchronous
operations. However, when many callbacks are nested, the
code can be complex and hard to read and understand.
To avoid callback hell, you can use a more modern way of
handling async operations known as promises. Promises
provide a more elegant way of handling the asynchronous
flow of a program compared to callback functions. This is the
focus of the next section.
How Do Promises Work?
A promise represents a way of handling asynchronous
operations in a more organized way. It serves the same
purpose as a callback but offers many additional capabilities
and a more readable syntax.
A promise in JavaScript is a placeholder for a future value or
action. By creating a promise, you are essentially telling the
JavaScript engine to "promise" to perform a specific action
and notify you once it is completed or fails.
Next, callback functions are then attached to the promise to
handle the outcome of the action. These callbacks will be
invoked when the promise is fulfilled (action completed
successfully) or rejected (action failed).
How to Create a Promise
To create a promise, you'll create a new instance of
the Promise object by calling the Promise constructor.
The constructor takes a single argument: a function
called executor. The "executor" function is called immediately
when the promise is created, and it takes two arguments:
a resolve function and a reject function.

const myPromise = new Promise(function(resolve, reject) =>


{})
console.log(myPromise);

As you can see, the promise has a pending status and


an undefined value. This is because nothing has been set up
for the promise object yet, so it's going to sit there in a
pending state forever without any value or result.

Now, let's set up myPromise to resolve with a string printed


to the console after 2 seconds.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello from the promise!");
}, 2000);
});

A promise has three states:


 Pending: initial state, neither fulfilled nor rejected.

 Fulfilled: meaning that an operation was completed

successfully.
 Rejected: meaning that an operation failed.

It's important to note that a promise is said to be settled


when it is resolved or rejected.
Now that you know how promises are created, let's look at
how you may consume them.

How to Consume a Promise


Consuming a promise involves the following steps:
1. Obtain a reference to the promise: To consume a
promise, you first need to obtain a reference to it. Based
on the code from the previous section, our reference to
a promise will be the myPromise object.
2. Attach callbacks to the promise: Once you have a
reference, you can attach callback functions by using
the .then and .catch methods. The .then method is
called when a promise is fulfilled and the .catch method
is called when a promise is rejected.
3. Wait for the promise to be fulfilled or rejected: Once
you've attached callbacks to the promise, you can wait
for the promise to be fulfilled or rejected.

myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
Once the promise is fulfilled, the .then callback method
will be called with the resolved value. And if the promise
is rejected, the .catch method will be called with an
error message.
You can also add the .finally() method, which will be
called after a promise is settled. This means
that .finally() will be invoked regardless of the status of a
promise (whether resolved or rejected).
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
//code here will be executed regardless of the status
//of a promise (fulfilled or rejected)
});

It's important to keep in mind that .then methods are


executed asynchronously and in order, each one waiting for
the previous one to be resolved, and that the returned value
of each .then will be passed as an argument to the next one.

You might also like