Asynchronous Programming in JavaScript
Asynchronous Programming in JavaScript
setTimeout(function() {
console.log("First timeout completed");
}, 2000);
console.log("End of script");
function fetchData(callback) {
setTimeout(() => {
const data = {name: "John", age: 30};
callback(data);
}, 3000);
}
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.
successfully.
Rejected: meaning that an operation failed.
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)
});