DEV Community

Cover image for Async Vs Sync, which is most preferrable?
Jhaemis-hack
Jhaemis-hack

Posted on • Edited on

Async Vs Sync, which is most preferrable?

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 and sixth line. Hence, this allows a non-blocking functionality in Js.

There are basically three forms of async model:

  1. async-await
  2. .then .Catch
  3. .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();

Enter fullscreen mode Exit fullscreen mode

Declared an async function.
Allows the use of await 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.
try...catch handles any errors that occur during the asynchronous operation.
For example, if the network request fails, the error will be caught and logged.

An async function declaration creates an AsyncFunction object. Each time
when an async function is called, it returns a new Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.

Async can also be used as a function.

Async functions can contain zero or more await expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of async and await enables the use of ordinary try/catch blocks around asynchronous code.

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url);
  } catch (e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}

Enter fullscreen mode Exit fullscreen mode

.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
    });

Enter fullscreen mode Exit fullscreen mode

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 using response.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 in 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
    });

Enter fullscreen mode Exit fullscreen mode

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)