top of page

Synchronous vs Asynchronous Coding in Wix Velo: A Comprehensive Guide

Updated: Oct 17, 2023


coding on WIX

With the emergence of Wix Velo, developers have been provided with a powerful platform to create robust web applications. One of the key decisions that developers have to make is whether to write synchronous or asynchronous code. This blog post aims to shed light on the differences between the two, providing examples and detailing the results of each.


1. The Basics


Synchronous Code: When you write synchronous code, each line is executed in order. It waits for the previous line to finish before moving to the next. This type of code is easy to write and understand, but it can lead to performance issues.


Asynchronous Code: In asynchronous code, some operations (like fetching data) are initiated and then set aside. The rest of the code keeps running without waiting for that operation to complete. When the operation is done, a callback or a promise resolves, and the result is processed.


2. Examples


a) Synchronous Code in Wix Velo

Here's our synchronous code with console.log statements:


import wixData from 'wix-data';

function fetchDataAndDisplay() {
    console.log("Starting to fetch data...");

    let results = wixData.query("myCollection").find();

    console.log("Data fetched!");

    $w("#myRepeater").data = results.items;

    console.log("Data displayed on repeater!");
}

fetchDataAndDisplay();

When you run this code:

  1. You'll see "Starting to fetch data..." in the console.

  2. It will then fetch the data. During this time, no other operations can occur.

  3. Once the data is fetched, you'll see "Data fetched!".

  4. The data is then displayed, and you'll see "Data displayed on repeater!".


b) Asynchronous Code in Wix Velo

Now, our asynchronous code with console.log statements:


import wixData from 'wix-data';

async function fetchDataAndDisplay() {
    console.log("Starting to fetch data asynchronously...");

    let results = await wixData.query("myCollection").find();

    console.log("Data fetched asynchronously!");

    $w("#myRepeater").data = results.items;

    console.log("Data displayed on repeater!");
}

fetchDataAndDisplay();

console.log("This might print before the data is fetched!");

When you run this code:

  1. You'll see "Starting to fetch data asynchronously..." in the console.

  2. The await will initiate the data fetch but won't block the rest of the code.

  3. Hence, "This might print before the data is fetched!" might print before the data fetching is complete, showcasing the non-blocking nature.

  4. Once the data is fetched, you'll see "Data fetched asynchronously!".

  5. The data is then displayed, and you'll see "Data displayed on repeater!".


3. Results

Synchronous Code:

Advantages:

  1. Simplicity: The line-by-line execution makes it easier to write and understand. Example: Let's consider you're baking. Following a recipe step by step, without skipping any step, is like synchronous coding. You won't start frosting the cake until it's baked and cooled, even if it takes hours.

  2. Predictability: The output and the flow are predictable since instructions are carried out in sequence. Example: In a bank queue, the next person is served only when the previous person's task is completed. It's easy to predict the sequence of service.

Drawbacks:

  1. Performance: It can lead to "blocking" behavior. For tasks that take a long time, the program can become unresponsive. Example: Imagine waiting in line to buy tickets at a movie theater, and the person in front takes 20 minutes to decide. Everyone else is blocked and has to wait.

  2. Not Ideal for I/O Operations: For operations like reading from databases or making API calls, the entire system has to wait for the response. Example: It's like reading a book and stopping everything else you're doing just to check a reference or fact online. Your reading is entirely halted until you get your answer.

Asynchronous Code:

Advantages:


Performance: The non-blocking nature can enhance the application's performance, allowing multiple operations to progress without waiting.

Example: In a restaurant, while one dish is being prepared, the chef starts working on another. This way, multiple dishes are in progress, optimizing kitchen operations.


Efficient for I/O: When you don't have to wait for operations like fetching data or reading a file, other parts of the program can continue.

Example: Imagine reading that same book but having a friend who can check references or facts for you. While they're looking up the info, you continue reading. Once they have the answer, they'll inform you, and you can decide when to process that information.


Drawbacks:


Complexity: Asynchronous code, especially with nested callbacks or managing multiple promises, can become challenging to write, read, and debug.

Example: It's like multitasking. You might be cooking, answering a call, and watching a show simultaneously. Handling all these tasks requires coordination and can be complicated. Missing a step in cooking might ruin the dish.


Callback Hell: When callbacks are nested within callbacks, the code becomes harder to read and maintain. This is colloquially referred to as "Callback Hell" or "Pyramid of Doom."

Example: Imagine planning a series of events where one's occurrence depends on the completion of the previous one. Like, before you can book a venue, you need to finalize the guest count. Before finalizing the guest count, you need RSVPs. Before getting RSVPs, you need to send out invites. These dependencies, if not managed well, can be chaotic.


Conclusion:

In the evolving landscape of web development, understanding the nuances of synchronous and asynchronous coding is crucial. Both approaches come with their merits and pitfalls. Synchronous coding shines in scenarios where simplicity and predictability are paramount. In contrast, asynchronous coding, with its non-blocking nature, can vastly improve performance, especially in operations that require waiting, such as I/O tasks.

However, like most choices in development, the decision between synchronous and asynchronous isn't absolute. It depends on the context, the needs of the project, and the desired user experience. It's essential to comprehend both paradigms to determine the best fit for your specific application.


Looking for expert guidance or assistance in your web development journey? CodeMasters Agency boasts a team of professionals skilled in the art of synchronous and asynchronous coding. Don't navigate the intricacies alone; let CodeMasters be your guiding compass in the world of web development. Contact us today!


Comments


Always stay ahead ! Subscribe now. 

Thanks for submitting!

bottom of page