According to the description of JavaScript(Js), we have been informed that Js is a single threaded language that enforces blocking programming model which will prevent codes from running haphazardly or randomly(i.e, runs in order from the first line of code to the last line of code).
Hence, in a block of codes JavaScript run the last line of code last.
However, an additional functionality that set JavaScript aside from every other language is the ability of the codes to run in no particular order. A good illustration will be to consider a restaurant ordering system. Let's say we have six(6) customers in the restaurant, and they all ordered for different delicacies.
the first ordered for pounded yam
the second order for white yam
the third ordered for white rice
the fourth, jollof rice
the fifth, beans
and the sixth, jollof spaghetti.
conventionally, the chefs should attend to the first customer, then the second and on and on to the sixth customer. That's the way normal Js works. Until it finishs running the first line of code the second won't run and if the fifth throws an error, it will never read the sixth line of code. However, if you have ever been to a standard restaurant, it just doesn't work that way. Rather than waiting for pounded yam to get served first, other cook in the kitchen will asynchronously start preparing for the other dishes that won't take more time. So it is possible for the sixth customer who requested for jollof spaghetti to get served first.
That is just how the asynchronous property of Js works. If the fourth line of code is set to async, Js will not wait for it before running the fifth line and sixth. Hence, this allows a non-blocking functionality in Js.
There are basically three forms of async model:
- async-await
- .then .Catch
- .finally()
async-await
A modern and clean way to work with promises. It makes asynchronous code look and behave more like synchronous code. await pauses the execution of the function until the promise resolves or rejects.
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.
com/posts/1'); // Wait for the fetch to complete
const data = await response.json(); // Wait for the response to be parsed as JSON
console.log('Data:', data); // Log the fetched data
} catch (error) {
console.error('Error:', error); // Handle any errors
}
}
fetchData();
Declared an
async
function.
Allows the use ofawait
inside the function.
Pauses the execution of the function until the promise resolves.
await fetch(...)
waits for the HTTP request to complete.
await response.json()
waits for the response body to be parsed as JSON.
Handles any errors that occur during the asynchronous operation.
For example, if the network request fails, the error will be caught and logged.
.then .catch
This shows how .then()
is used to chain promise-based operations and handle asynchronous data fetching
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the response as JSON
})
.then(data => {
console.log('Data:', data); // Log the fetched data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
});
Initiates an HTTP request to the provided URL.
Returns a promise that resolves to the HTTP response.
If successful, the response is parsed as JSON usingresponse.json()
,
Second.then()
Block: Handles the parsed JSON data from the first.then()
.
Logs the data to the console.
catch Block: Handles errors that occur in any of the.then()
blocks or during the fetch call.
Logs the error message to the console
.finally()
It ensures that a specific block of code runs no matter what happens with the promise.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the response as JSON
})
.then(data => {
console.log('Data:', data); // Log the fetched data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
})
.finally(() => {
console.log('Request completed.'); // Executes regardless of success or failure
});
The
.finally()
block is executed after the promise is settled, regardless of whether it was fulfilled or rejected.
It’s useful for cleanup tasks, such as hiding a loading spinner or resetting variables, that should run no matter what.
If the promise is fulfilled: The.then()
blocks execute, followed by.finally()
.
If the promise is rejected: The.catch()
block executes, followed by.finally()
Now, you can decide which is best for your project.
Top comments (0)